Android - 缩放和压缩位图 [英] Android - Scale and compress a bitmap

查看:121
本文介绍了Android - 缩放和压缩位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款具有相机捕捉和照片上传功能的Android应用。如果设备具有高分辨率相机,捕获的图像尺寸将非常大(1~3MB或更多)。

由于应用需要将此图像上传到服务器,我需要在上传之前压缩图像。例如,如果相机捕获了1920x1080全分辨率照片,理想的输出是保持图像的16:9比例,将其压缩为640x360图像以降低图像质量并使其以字节为单位缩小。 / p>

这是我的代码(从谷歌引用):

  / * * 
*此类提供的方法可以帮助压缩图像大小。
*
* /
公共类ImageCompressHelper {

/ **
*计算压缩图像的数量
* @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;

if(height> reqHeight || width> reqWidth){

final int halfHeight = height / 2;
final int halfWidth = width / 2;

//计算2的幂的最大inSampleSize值,并保持
//高度和宽度都大于请求的高度和宽度。
while((halfHeight / inSampleSize)> reqHeight
&&(halfWidth / inSampleSize)> reqWidth){
inSampleSize * = 2;
}
}

返回inSampleSize;
}

/ **
*将图片大小调整为480x800
* @param filePath
* @return
* /
public static Bitmap getSmallBitmap(String filePath){

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

MyLogger.Verbose(原始图像大小为:+ originalSize +bytes。);

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

//根据预设比率计算inSampleSize
options.inSampleSize = calculateInSampleSize(options,480,800);

//用inSampleSize解码位图设置
options.inJustDecodeBounds = false;

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

MyLogger.Verbose(压缩图像大小为+ sizeOf(compressedImage)+bytes);

返回compressedImage;
}

以上代码的问题是:


  1. 它无法保持比例,代码强制图像调整为480x800。如果用户以另一个比例捕获图像,压缩后图像看起来不会很好。

  2. 它运行不正常。无论原始文件大小是多少,代码都会始终将图像大小更改为7990272byte。如果原始图像尺寸已经非常小,它会变大(我的测试结果是拍摄我的墙,这是非常单色):



    原始图像大小为:990092字节。

    压缩图像大小为7990272字节


我在问是否有更好的方法压缩照片以便顺利上传?

解决方案


  1. 您需要决定宽度或高度的限制(显然不是两者)。然后用计算的图像替换那些固定的图像尺寸,例如:

      int targetWidth = 640; //你的任意固定限制
    int targetHeight =(int)(originalHeight * targetWidth /(double)originalWidth); //强制转换以避免截断

    (根据需要添加横向/纵向方向的检查和计算方法。 )


  2. 正如@harism所评论的那样:你提到的大尺寸是480x800位图的原始大小,而不是文件大小,在你的情况下应该是JPEG。你是如何保存该位图的?BTW?您的代码似乎不包含保存部分。



    请参阅这个问题在这里提供帮助,关键是:

      OutputStream imagefile = new FileOutputStream(/ your / file / name.jpg); 
    //使用JPEG将位图写入文件,为JPEG写入80%质量提示:
    bitmap.compress(CompressFormat.JPEG,80,imagefile);



I am working on an android app, which has camera capture and photo uploading feature. If the device has a high resolution camera, the captured image size will be really large (1~3MB or more).
Since the app will need to upload this image to server, I will need to compress the image before uploading. If the camera captured a 1920x1080 full-res photo for example, the ideal output is to keep a 16:9 ratio of the image, compress it to be a 640x360 image to reduce some image quality and make it a smaller size in bytes.

Here is my code (referenced from google):

/**
 * this class provide methods that can help compress the image size.
 *
 */
public class ImageCompressHelper {

/**
 * 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) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

    final int halfHeight = height / 2;
    final int halfWidth = width / 2;

    // Calculate the largest inSampleSize value that is a power of 2 and keeps both
    // height and width larger than the requested height and width.
    while ((halfHeight / inSampleSize) > reqHeight
            && (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
    }
}

return inSampleSize;
}

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

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

    MyLogger.Verbose("Original image size is: " + originalSize + " bytes.");

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

    MyLogger.Verbose("Compressed image size is " + sizeOf(compressedImage) + " bytes");

    return compressedImage;
}

The problem with the above code is:

  1. It cannot keep the ratio, the code is forcing the image to resized to 480x800. if user captured a image in another ratio, the image will not look good after compress.
  2. It doesn't functioning well. The code will always change the image size to 7990272byte no matter what the original file size is. If the original image size is pretty small already, it will make it big (my test result to take a picture of my wall, which is pretty much mono-colored):

    Original image size is: 990092 bytes.
    Compressed image size is 7990272 bytes

I am asking if there's suggestion of a better way to compress photo so it can be uploaded smoothly?

解决方案

  1. You need to decide on a limit for either your width or height (not both, obviously). Then replace those fixed image sizes with calculated ones, say:

    int targetWidth = 640; // your arbitrary fixed limit
    int targetHeight = (int) (originalHeight * targetWidth / (double) originalWidth); // casts to avoid truncating
    

    (Add checks and calculation alternatives for landscape / portrait orientation, as needed.)

  2. As @harism also commented: the large size you mentioned is the raw size of that 480x800 bitmap, not the file size, which should be a JPEG in your case. How are you going about saving that bitmap, BTW? Your code doesn't seem to contain the saving part.

    See this question here for help on that, with the key being something like:

    OutputStream imagefile = new FileOutputStream("/your/file/name.jpg");
    // Write 'bitmap' to file using JPEG and 80% quality hint for JPEG:
    bitmap.compress(CompressFormat.JPEG, 80, imagefile);
    

这篇关于Android - 缩放和压缩位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆