如何在Android中调整位图的大小?

我从个人远程数据库中获取了一个Base64字符串的位图,( encodedImage是表示使用Base64的图像的字符串): android

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。 布局

有人能够告诉我代码来调整大小吗? post

我发现的示例没法应用于得到的base64字符串位图。 this


#1楼

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(); 内存泄漏。 请注意,若是您将前一个对象用于其余目的,请相应地进行处理。 spa


#2楼

若是已经有位图,则能够使用如下代码来调整大小: code

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

#3楼

profileImage.setImageBitmap(
    Bitmap.createScaledBitmap(
        BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length), 
        80, 80, false
    )
);

#4楼

试试这个代码: 对象

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

我但愿它有用。 图片


#5楼

有人问在这种状况下如何保持宽高比: 内存

计算用于缩放的因子,并将其用于两个维度。 假设您但愿图片的高度为屏幕的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);

要得到屏幕分辨率,您能够使用如下解决方案: 以像素为单位获取屏幕尺寸