programing

Android에서 비트맵 크기를 조정하는 방법?

lastcode 2023. 8. 20. 11:13
반응형

Android에서 비트맵 크기를 조정하는 방법?

이 있습니다.encodedImageBase64)로 이미지를 나타내는 문자열입니다.

profileImage = (ImageView)findViewById(R.id.profileImage);

byte[] imageAsBytes=null;
try {
    imageAsBytes = Base64.decode(encodedImage.getBytes());
} catch (IOException e) {e.printStackTrace();}

profileImage.setImageBitmap(
    BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
);

프로필 이미지는 내 이미지 보기입니다.

이 를 제 . 하지만 이 이미지를 표시하기 전에 크기를 조정해야 합니다.ImageView내 레이아웃의.120x120x120으로 .

누가 크기를 조정할 코드를 알려줄 수 있나요?

찾은 예제는 base64 문자열이 획득한 비트맵에 적용되지 않았습니다.

변경:

profileImage.setImageBitmap(
    BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)

받는 사람:

Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));
import android.graphics.Matrix
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // CREATE A MATRIX FOR THE MANIPULATION
    Matrix matrix = new Matrix();
    // RESIZE THE BIT MAP
    matrix.postScale(scaleWidth, scaleHeight);

    // "RECREATE" THE NEW BITMAP
    Bitmap resizedBitmap = Bitmap.createBitmap(
        bm, 0, 0, width, height, matrix, false);
    bm.recycle();
    return resizedBitmap;
}

@ @aveschini 가제한안대, 습니다추했편가를 했습니다.bm.recycle();메모리 누수를 방지하기 위해.이전 개체를 다른 용도로 사용하는 경우에는 그에 따라 처리하십시오.

비트맵이 이미 있는 경우 다음 코드를 사용하여 크기를 조정할 수 있습니다.

Bitmap originalBitmap = <original initialization>;
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
    originalBitmap, newWidth, newHeight, false);

가로 세로 비율을 기준으로 한 확장:

float aspectRatio = yourSelectedImage.getWidth() / 
    (float) yourSelectedImage.getHeight();
int width = 480;
int height = Math.round(width / aspectRatio);

yourSelectedImage = Bitmap.createScaledBitmap(
    yourSelectedImage, width, height, false);

너비 변경 대신 높이를 기준으로 사용하는 방법:

int height = 480;
int width = Math.round(height * aspectRatio);

가로 세로 비율을 유지하면서 목표 최대 크기 및 너비로 비트맵 크기 조정:

int maxHeight = 2000;
int maxWidth = 2000;    
float scale = Math.min(((float)maxHeight / bitmap.getWidth()), ((float)maxWidth / bitmap.getHeight()));

Matrix matrix = new Matrix();
matrix.postScale(scale, scale);

bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

이 코드를 사용해 보십시오.

BitmapDrawable drawable = (BitmapDrawable) imgview.getDrawable();
Bitmap bmp = drawable.getBitmap();
Bitmap b = Bitmap.createScaledBitmap(bmp, 120, 120, false);

유용하게 쓰였으면 좋겠습니다.

누군가가 이 상황에서 가로 세로 비율을 유지하는 방법을 물었습니다.

배율 조정에 사용 중인 요인을 계산하여 두 차원 모두에 사용합니다.이미지의 높이가 화면의 20%라고 가정해 보겠습니다.

int scaleToUse = 20; // this will be our percentage
Bitmap bmp = BitmapFactory.decodeResource(
    context.getResources(), R.drawable.mypng);
int sizeY = screenResolution.y * scaleToUse / 100;
int sizeX = bmp.getWidth() * sizeY / bmp.getHeight();
Bitmap scaled = Bitmap.createScaledBitmap(bmp, sizeX, sizeY, false);

화면 해상도를 얻으려면 다음 솔루션을 사용합니다.화면 크기(픽셀) 가져오기

승인된 답변이 올바르더라도 크기가 조정되지 않습니다.Bitmap동일한 가로 세로 비율을 유지합니다.크기 조정 방법을 찾는 경우Bitmap동일한 가로 세로 비율을 유지하면 다음 유틸리티 기능을 사용할 수 있습니다.기능에 대한 자세한 내용과 설명은 이 링크에 나와 있습니다.

public static Bitmap resizeBitmap(Bitmap source, int maxLength) {
       try {
           if (source.getHeight() >= source.getWidth()) {
               int targetHeight = maxLength;
               if (source.getHeight() <= targetHeight) { // if image already smaller than the required height
                   return source;
               }

               double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
               int targetWidth = (int) (targetHeight * aspectRatio);

               Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
               if (result != source) {
               }
               return result;
           } else {
               int targetWidth = maxLength;

               if (source.getWidth() <= targetWidth) { // if image already smaller than the required height
                   return source;
               }

               double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
               int targetHeight = (int) (targetWidth * aspectRatio);

               Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
               if (result != source) {
               }
               return result;

           }
       }
       catch (Exception e)
       {
           return source;
       }
   }
  public Bitmap scaleBitmap(Bitmap mBitmap) {
        int ScaleSize = 250;//max Height or width to Scale
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        float excessSizeRatio = width > height ? width / ScaleSize : height / ScaleSize;
         Bitmap bitmap = Bitmap.createBitmap(
                mBitmap, 0, 0,(int) (width/excessSizeRatio),(int) (height/excessSizeRatio));
        //mBitmap.recycle(); if you are not using mBitmap Obj
        return bitmap;
    }
public static Bitmap resizeBitmapByScale(
            Bitmap bitmap, float scale, boolean recycle) {
        int width = Math.round(bitmap.getWidth() * scale);
        int height = Math.round(bitmap.getHeight() * scale);
        if (width == bitmap.getWidth()
                && height == bitmap.getHeight()) return bitmap;
        Bitmap target = Bitmap.createBitmap(width, height, getConfig(bitmap));
        Canvas canvas = new Canvas(target);
        canvas.scale(scale, scale);
        Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
        canvas.drawBitmap(bitmap, 0, 0, paint);
        if (recycle) bitmap.recycle();
        return target;
    }
    private static Bitmap.Config getConfig(Bitmap bitmap) {
        Bitmap.Config config = bitmap.getConfig();
        if (config == null) {
            config = Bitmap.Config.ARGB_8888;
        }
        return config;
    }
      Try this kotlin code for resize....Where Max size any size you 
      want

      fun getResizedBitmap(image: Bitmap?, maxSize: Int): Bitmap {
    var width = image!!.width
    var height = image.height
    val bitmapRatio = width.toFloat() / height.toFloat()
     if (bitmapRatio > 0) {
        width = maxSize
        height = (width / bitmapRatio).toInt()
     } else {
        height = maxSize
         width = (height * bitmapRatio).toInt()
     }
         return Bitmap.createScaledBitmap(image, width, height, true)
     }

사용해 보십시오.이 함수는 비트맵의 크기를 비례적으로 조정합니다.를 "하면 "X"로 설정됩니다.newDimensionXorY새 너비로 처리되며 새 높이를 "Y"로 설정할 경우.

public Bitmap getProportionalBitmap(Bitmap bitmap, 
                                    int newDimensionXorY, 
                                    String XorY) {
    if (bitmap == null) {
        return null;
    }

    float xyRatio = 0;
    int newWidth = 0;
    int newHeight = 0;

    if (XorY.toLowerCase().equals("x")) {
        xyRatio = (float) newDimensionXorY / bitmap.getWidth();
        newHeight = (int) (bitmap.getHeight() * xyRatio);
        bitmap = Bitmap.createScaledBitmap(
            bitmap, newDimensionXorY, newHeight, true);
    } else if (XorY.toLowerCase().equals("y")) {
        xyRatio = (float) newDimensionXorY / bitmap.getHeight();
        newWidth = (int) (bitmap.getWidth() * xyRatio);
        bitmap = Bitmap.createScaledBitmap(
            bitmap, newWidth, newDimensionXorY, true);
    }
    return bitmap;
}
profileImage.setImageBitmap(
    Bitmap.createScaledBitmap(
        BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length), 
        80, 80, false
    )
);

모든 디스플레이 크기를 기준으로 비트맵 크기 조정

public Bitmap bitmapResize(Bitmap imageBitmap) {

    Bitmap bitmap = imageBitmap;
    float heightbmp = bitmap.getHeight();
    float widthbmp = bitmap.getWidth();

    // Get Screen width
    DisplayMetrics displaymetrics = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    float height = displaymetrics.heightPixels / 3;
    float width = displaymetrics.widthPixels / 3;

    int convertHeight = (int) hight, convertWidth = (int) width;

    // higher
    if (heightbmp > height) {
        convertHeight = (int) height - 20;
        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth,
                convertHighet, true);
    }

    // wider
    if (widthbmp > width) {
        convertWidth = (int) width - 20;
        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth,
                convertHeight, true);
    }

    return bitmap;
}

API 19 기준으로 비트맵 set Width(int width)와 set Height(int height)가 존재합니다.http://developer.android.com/reference/android/graphics/Bitmap.html

/**
 * Kotlin method for Bitmap scaling
 * @param bitmap the bitmap to be scaled
 * @param pixel  the target pixel size
 * @param width  the width
 * @param height the height
 * @param max    the max(height, width)
 * @return the scaled bitmap
 */
fun scaleBitmap(bitmap:Bitmap, pixel:Float, width:Int, height:Int, max:Int):Bitmap {
    val scale = px / max
    val h = Math.round(scale * height)
    val w = Math.round(scale * width)
    return Bitmap.createScaledBitmap(bitmap, w, h, true)
  }

가로 세로 비율을 유지하면서,

  public Bitmap resizeBitmap(Bitmap source, int width,int height) {
    if(source.getHeight() == height && source.getWidth() == width) return source;
    int maxLength=Math.min(width,height);
    try {
        source=source.copy(source.getConfig(),true);
        if (source.getHeight() <= source.getWidth()) {
            if (source.getHeight() <= maxLength) { // if image already smaller than the required height
                return source;
            }

            double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
            int targetWidth = (int) (maxLength * aspectRatio);

            return Bitmap.createScaledBitmap(source, targetWidth, maxLength, false);
        } else {

            if (source.getWidth() <= maxLength) { // if image already smaller than the required height
                return source;
            }

            double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
            int targetHeight = (int) (maxLength * aspectRatio);

            return Bitmap.createScaledBitmap(source, maxLength, targetHeight, false);

        }
    }
    catch (Exception e)
    {
        return source;
    }
}

이전 답변에서는 이미지의 크기를 조정하고 가로 세로 비율을 처리하지만 앨리어싱이 발생하지 않도록 재샘플링 자체를 수행해야 합니다.규모를 관리하는 것은 논쟁을 올바르게 해결하는 문제입니다.표준 스케일링 호출의 출력 영상 품질에 대해 많은 의견이 있습니다. 영상 품질을 유지하려면 표준 호출을 사용해야 합니다.

Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, true);

마지막 인수가 에일리어스를 방지하기 위해 재샘플링에 대한 이중 선형 필터링을 수행하기 때문에 로 설정됩니다.별칭에 대한 자세한 내용은 여기를 참조하십시오. https://en.wikipedia.org/wiki/Aliasing

Android 설명서에서:

https://developer.android.com/reference/android/graphics/Bitmap#createScaledBitmap(android.graphics.Bitmap,%20int,%20int,%20boolean)


public static Bitmap createScaledBitmap (Bitmap src, 
                int dstWidth, 
                int dstHeight, 
                boolean filter)

filter : boolean, 비트맵의 크기를 조정할 때 양방향 필터링을 사용할지 여부를 지정합니다.이 값이 참이면 성능이 저하되는 대신 이미지 품질이 향상된 스케일링을 할 때 이중 선형 필터링이 사용됩니다.이 값이 거짓이면 영상 화질이 더 나쁘지만 더 빠른 근거리 스케일링이 대신 사용됩니다.권장 기본값은 필터를 'true'로 설정하는 것입니다. 이중 선형 필터링의 비용은 일반적으로 최소이며 향상된 이미지 품질이 상당하기 때문입니다.

* For resize bitmap with width and height ratio.    

public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
            int width = image.getWidth();
            int height = image.getHeight();
    
            float bitmapRatio = (float) width / (float) height;
            if (bitmapRatio > 1) {
                width = maxSize;
                height = (int) (width / bitmapRatio);
            } else {
                height = maxSize;
                width = (int) (height * bitmapRatio);
            }
            return Bitmap.createScaledBitmap(image, width, height, true);
        }

행렬을 적용합니다.크기에 맞게 조정합니다.CENTER)는 새 비트맵을 가져오기 위해 가로 세로 비율을 유지합니다.

public static Bitmap getScaledwonBitmap(Bitmap srcBmp, int deisredWidth, int desiredHeight) {
        
            Matrix matrix = new Matrix();
            matrix.setRectToRect(new RectF(0, 0, srcBmp.getWidth(), srcBmp.getHeight()),
                    new RectF(0, 0, deisredWidth, desiredHeight),
                    Matrix.ScaleToFit.CENTER);
           return Bitmap.createBitmap(srcBmp, 0, 0, srcBmp.getWidth(), srcBmp.getHeight(), matrix, true);
        
    }

단순하게 설명하면 됩니다.

fun Bitmap.scaleWith(scale: Float) = Bitmap.createScaledBitmap(
    this,
    (width * scale).toInt(),
    (height * scale).toInt(),
    false
)

여기서 스케일 업 또는 스케일 다운을 위해 사용할 수 있습니다.scale = 1.0동일한 크기로 간주되므로 20%까지 확장할 수 있습니다.scale = 1.2

언급URL : https://stackoverflow.com/questions/4837715/how-to-resize-a-bitmap-in-android

반응형