如何将图像(位图)调整为给定大小?

Dam*_*mir 48 android bitmap

如何以编程方式将图像(位图)调整为800*480?我已经在我的应用程序中检索到了大约1MB的图片,我需要将其缩小到800*480我已经加载了该图片并对其进行了压缩但是我该如何缩小它:

ByteArrayOutputStream bos = new ByteArrayOutputStream(8192);
photo.compress(CompressFormat.JPEG, 25, bos); 
Run Code Online (Sandbox Code Playgroud)

Pad*_*mar 98

Bitmap scaledBitmap = scaleDown(realImage, MAX_IMAGE_SIZE, true);
Run Code Online (Sandbox Code Playgroud)

缩小方法:

public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
        boolean filter) {
    float ratio = Math.min(
            (float) maxImageSize / realImage.getWidth(),
            (float) maxImageSize / realImage.getHeight());
    int width = Math.round((float) ratio * realImage.getWidth());
    int height = Math.round((float) ratio * realImage.getHeight());

    Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
            height, filter);
    return newBitmap;
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,此方法也会扩大规模.为了确保仅缩小图像,请检测结果比率是否小于1 (8认同)
  • 我得到一个错误`尝试在空对象引用上调用虚拟方法'void android.graphics.Bitmap.setHasAlpha(boolean)' (2认同)
  • 这就是我想要的东西,谢谢你完美缩小并将位图按比例放大到所需尺寸而不改变宽高比. (2认同)
  • 如果你想防止放大,只需在 `newBitmap` 对象初始化之前添加 `if (ratio >= 1.0){ return realImage;}`。 (2认同)
  • 伟大的解决方案......防止失真,这是我需要的. (2认同)

Vai*_*iya 15

 Bitmap yourBitmap;
 Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
Run Code Online (Sandbox Code Playgroud)

要么:

 resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);
Run Code Online (Sandbox Code Playgroud)


Jin*_*n35 11

您可以使用canvas.drawBitmap并使用提供矩阵来缩放位图,例如:

public static Bitmap scaleBitmap(Bitmap bitmap, int wantedWidth, int wantedHeight) {
        Bitmap output = Bitmap.createBitmap(wantedWidth, wantedHeight, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        Matrix m = new Matrix();
        m.setScale((float) wantedWidth / bitmap.getWidth(), (float) wantedHeight / bitmap.getHeight());
        canvas.drawBitmap(bitmap, m, new Paint());

        return output;
    }
Run Code Online (Sandbox Code Playgroud)