Android – 缩小图像文件大小

我有一个URI图像文件,我想减小它的大小来上传它。 初始图像文件的大小取决于手机到手机(可以是2MB,可以是500KB),但是我希望最终大小约为200KB,以便我可以上传它。
从我读到的,我有(至less)2个select:

  • 使用BitmapFactory.Options.inSampleSize ,对原始图像进行二次采样并获得较小的图像;
  • 使用Bitmap.compress压缩指定压缩质量的图像。

什么是最好的select?


我正在考虑最初调整图像宽度/高度,直到宽度或高度超过1000像素(如1024×768等),然后压缩图像质量下降,直到文件大小超过200KB。 这是一个例子:

int MAX_IMAGE_SIZE = 200 * 1024; // max final file size Bitmap bmpPic = BitmapFactory.decodeFile(fileUri.getPath()); if ((bmpPic.getWidth() >= 1024) && (bmpPic.getHeight() >= 1024)) { BitmapFactory.Options bmpOptions = new BitmapFactory.Options(); bmpOptions.inSampleSize = 1; while ((bmpPic.getWidth() >= 1024) && (bmpPic.getHeight() >= 1024)) { bmpOptions.inSampleSize++; bmpPic = BitmapFactory.decodeFile(fileUri.getPath(), bmpOptions); } Log.d(TAG, "Resize: " + bmpOptions.inSampleSize); } int compressQuality = 104; // quality decreasing by 5 every loop. (start from 99) int streamLength = MAX_IMAGE_SIZE; while (streamLength >= MAX_IMAGE_SIZE) { ByteArrayOutputStream bmpStream = new ByteArrayOutputStream(); compressQuality -= 5; Log.d(TAG, "Quality: " + compressQuality); bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream); byte[] bmpPicByteArray = bmpStream.toByteArray(); streamLength = bmpPicByteArray.length; Log.d(TAG, "Size: " + streamLength); } try { FileOutputStream bmpFile = new FileOutputStream(finalPath); bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpFile); bmpFile.flush(); bmpFile.close(); } catch (Exception e) { Log.e(TAG, "Error on saving file"); } 

有没有更好的方法来做到这一点? 我应该尝试继续使用所有2种方法还是只使用一种? 谢谢

使用Bitmap.compress()您只需指定压缩algorithm,并通过压缩操作需要相当多的时间。 如果您需要使用缩小尺寸来减less图像的内存分配,则需要使用Bitmap.Options对图像进行Bitmap.Options ,首先计算位图边界,然后将其解码为指定的大小。

我在StackOverflow上find的最好的例子就是这个 。

我发现的大多数答案只是我必须拼凑在一起得到一个工作代码,这是张贴在下面

  public void compressBitmap(File file, int sampleSize, int quality) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = sampleSize; FileInputStream inputStream = new FileInputStream(file); Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, options); inputStream.close(); FileOutputStream outputStream = new FileOutputStream("location to save"); selectedBitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream); outputStream.close(); long lengthInKb = photo.length() / 1024; //in kb if (lengthInKb > SIZE_LIMIT) { compressBitmap(file, (sampleSize*2), (quality/4)); } selectedBitmap.recycle(); } catch (Exception e) { e.printStackTrace(); } } 

2个参数的sampleSize和quality都起着重要的作用

sampleSize用于对原始图像进行二次采样,并返回一个较小的图像 ,即
SampleSize == 4返回的图像是原始宽度/高度的1/4。

质量用于提示压缩机 ,input范围在0-100之间。 0表示小尺寸的压缩,100表示​​最大质量的压缩