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

398

我有一个位图,是从我的远程数据库中取出的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字符串获取的位图。


可能是在Android中调整位图大小的重复问题。 - Sagar Pilkhwal
@SagarPilkhwal 这个问题先被问到了。 - 김선달
21个回答

4
      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)
     }

3
尝试这个: 这个函数可以按比例调整位图的大小。当最后一个参数设置为“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;
}

3

根据任意显示器大小调整位图大小

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;
}

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

1
保持纵横比,
  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;
    }
}

1

1
/**
 * 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)
  }

0

简单明了就好:

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

你可以使用它来进行缩放,scale = 1.0 被认为是相同的大小,所以要增加20%的缩放比例将会是 scale = 1.2


0

使用Matrix.ScaleToFit.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);
        
    }

0

虽然之前的答案可以缩放图像并处理宽高比,但重新采样本身应该这样做,以避免出现混叠。处理比例是正确修复参数的问题。有许多关于标准缩放调用输出图像质量的评论。为了保持图像质量,应使用标准调用:

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

将最后一个参数设置为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:布尔值,当缩放位图时是否应使用双线性过滤。如果为true,则在缩放时将使用双线性过滤,这会以更差的性能为代价提供更好的图像质量。如果为false,则改用最近邻缩放,这将导致较差的图像质量但速度更快。建议将filter默认设置为“true”,因为双线性过滤的成本通常很小,而改进的图像质量非常显著。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接