안드로이드에서 비트 맵의 크기를 조정하는 방법?
원격 데이터베이스에서 Base64 문자열의 비트 맵을 가져 왔습니다 ( encodedImage
Base64로 이미지를 나타내는 문자열 임).
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)
);
profileImage는 내 ImageView입니다
좋아,하지만 ImageView
내 레이아웃 에 표시하기 전에이 이미지의 크기를 조정해야 합니다. 120x120으로 크기를 조정해야합니다.
누군가 크기를 조정하는 코드를 말해 줄 수 있습니까?
내가 찾은 예제는 얻은 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);
너비의 기본 intead로 높이를 사용하려면 다음으로 변경하십시오.
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);
화면 해상도를 얻는 방법은 다음과 같습니다. 화면 크기를 픽셀 단위 로 가져옵니다.
이것을보십시오 :이 함수는 비트 맵의 크기를 비례 적으로 조정합니다. 마지막 매개 변수가 "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 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;
}
모든 디스플레이 크기에 따른 비트 맵 크기 조정
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부터 비트 맵 setWidth (int width) 및 setHeight (int height)가 존재합니다. http://developer.android.com/reference/android/graphics/Bitmap.html
참고 URL : https://stackoverflow.com/questions/4837715/how-to-resize-a-bitmap-in-android
'Programing' 카테고리의 다른 글
Java로 사용자 입력을 받으려면 어떻게해야합니까? (0) | 2020.03.12 |
---|---|
Excel에서 전체 열에 수식을 적용하는 바로 가기 (0) | 2020.03.12 |
Android에서 뷰 배경색의 애니메이션 변경 (0) | 2020.03.12 |
기존 배열에서 하위 배열 얻기 (0) | 2020.03.11 |
내 레지스트리없이 개인 NPM 모듈을 설치하는 방법은 무엇입니까? (0) | 2020.03.11 |