Android压缩位图

3

在我注意到Bitmap类中有一个压缩方法之前,我已经写了这个方法。

/**
 * Calcuate how much to compress the image
 * @param options
 * @param reqWidth
 * @param reqHeight
 * @return
 */
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {

    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1; // default to not zoom image

    if (height > reqHeight || width > reqWidth) {
             final int heightRatio = Math.round((float) height/ (float) reqHeight);
             final int widthRatio = Math.round((float) width / (float) reqWidth);
             inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
        return inSampleSize;
}

/**
 * resize image to 480x800
 * @param filePath
 * @return
 */
public static Bitmap getSmallBitmap(String filePath) {

    File file = new File(filePath);
    long originalSize = file.length();

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    // Calculate inSampleSize based on a preset ratio
    options.inSampleSize = calculateInSampleSize(options, 480, 800);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    Bitmap compressedImage = BitmapFactory.decodeFile(filePath, options);


    return compressedImage;
}

我在想,相较于内置的 Compress 方法,我应该继续使用这个方法还是切换到内置的方法?它们有什么区别?


请查看此链接:https://dev59.com/r8zts4cB2Jgan1znn0jY - Prashanth Debbadwar
2个回答

2

基本上

在上面的代码中,你所做的就是调整图像大小,由于使用了SampleSize,因此不会损失太多图像质量。

compress(Bitmap.CompressFormat format, int quality, OutputStream stream)

当你想要改变imageFormat或者通过quality参数0 - 100来降低图像的质量时,就可以使用这个方法。支持的Bitmap.CompressFormat JPEGBitmap.CompressFormat PNGBitmap.CompressFormat WEBP


2
你的方法符合加载大位图指南 Loading Large Bitmap
  • 磁盘上有大文件
  • 内存中有小位图
compress() 方法将大位图转换为小位图:
  • 内存中有大位图
  • 磁盘上有小位图(IOStream)(可能是不同格式)
如果我需要从文件加载位图并放到不同尺寸的ImageViews中,我会使用您的方法。

嗯,实际上我刚刚进行了一些测试,看起来我的代码不会减少地图。 - Allan Jiang
也许你的位图已经足够小了?此外,你的calculateInSampleSize()缺少一个迭代循环。只需复制并粘贴Google的代码作为起点。 - Y2i

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