android - 将位图大小调整为更小的位图

标签 android bitmap android-canvas

我有一个位图列表。 我想要的是获取这些位图,并在 Canvas 的帮助下,使用我拥有的位图列表中的按比例缩小的图像(也就是说,使它们非常小)创建一个新的位图。

我已经设法做到了,但是由于缩小比例,图像看起来很糟糕。 我已经尝试了很多东西,设置,创建新 Canvas 等。

第一个简单的解决方案看起来像这样(下面的代码),但是,正如我所说,图像看起来很糟糕。

public static Bitmap folderBitmap(Bitmap bitmap[]) {

    Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565);
    Canvas c = new Canvas(b);

    c.drawARGB(255, 255, 255, 255);

    Paint paint = new Paint();
    paint.setAntiAlias(false);
    paint.setFilterBitmap(false);
    paint.setDither(true);

    c.drawBitmap(getBit(bitmap), 4, 4, paint);
    c.drawBitmap(getBit(bitmap), 35, 4, paint);
    c.drawBitmap(getBit(bitmap), 67, 4, paint);

    c.drawBitmap(getBit(bitmap), 4, 35, null);
    c.drawBitmap(getBit(bitmap), 35, 35, null);
    c.drawBitmap(getBit(bitmap), 67, 35, null);

    c.drawBitmap(getBit(bitmap), 4, 67, null);
    c.drawBitmap(getBit(bitmap), 35, 67, null);
    c.drawBitmap(getBit(bitmap), 67, 67, null);

    return b;
}

private static Bitmap getBit(Bitmap[] b) {
    Bitmap newBitmap = Bitmap.createScaledBitmap(b[getR()], 28, 28, false);

    return newBitmap;
}

private static int getR() {
    Random r = new Random();
    int rint = r.nextInt(8);
    return rint;
}

糟糕透顶的意思是,它们看起来像素化且不清晰。

最佳答案

使用inSampleSize 缩放位图。来自文档

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.

例如:

 BitmapFactory.Options opts = new BitmapFactory.Options();
 opt.inSampleSize = 4;
 Bitmap newBitmap = BitmapFactory.decodeFile(filePath, opts);

关于android - 将位图大小调整为更小的位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17696984/

相关文章:

android - 在 android 中显示 gif

Android - 级联可绘制文件夹和默认可绘制对象

android - 如何将 aar 库上传到 Nexus?

java - BitmapFactory : Unable to decode stream: java. io.FileNotFoundException:打开失败:ENOENT(没有这样的文件或目录)

android - 将 .cgi 流图像格式保存为视频

安卓编程 : How to draw multiline text in a rectangle?

java - 使用 canvas.drawBitmap 时位图重叠

java - Android AudioData追加到结束

java - Bitmap 对象是否通过引用保存在内存中?

java - Android绘图应用程序中的撤消按钮