android - 如何在不影响位图大小的情况下降低位图质量

标签 android bitmap bitmapfactory

有没有一种方法可以在 android 中将 115kb 的图像压缩为 4kb 而不影响它的大小?。只是降低它的质量?

我只知道用

  • 减少大小和质量的 BitmapFactory.Options

  • Bitmap.compress 不提供以字节为单位指定大小的选项。

公共(public)位图压缩图像(字符串图像路径){

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
   bmp = BitmapFactory.decodeStream(new FileInputStream(imagePath),null, options);


  options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
  options.inJustDecodeBounds = false;
    bmp = BitmapFactory.decodeStream(new FileInputStream(imagePath),null, options);

  return bmp;
}



public  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 heightRatio = Math.round((float) height / (float) reqHeight);
    final int widthRatio = Math.round((float) width / (float) reqWidth);
    inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
  }
  final float totalPixels = width * height;
  final float totalReqPixelsCap = reqWidth * reqHeight * 2;

  while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
    inSampleSize++;
  }

  return inSampleSize;
}

最佳答案

图像调整大小意味着您将缩短图像的分辨率。假设用户选择 1000*1000 像素的图像。您要将图像转换为 300*300 图像。因此图像尺寸将减小。

图像压缩是在不影响分辨率的情况下减小图像的文件大小。当然,降低文件大小会影响图像质量。有许多可用的压缩算法可以在不影响图像质量的情况下减小文件大小。

我在这里找到的一个方便的方法是:

    Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());

给予

12-07 17:43:36.333: E/Original dimensions(278): 1024 768 12-07

17:43:36.333: E/Compressed dimensions(278): 1024 768

关于android - 如何在不影响位图大小的情况下降低位图质量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34768408/

相关文章:

android - 将许多大位图图像加载为缩略图 - Android

java - 在 Android 上将 Canvas 保存为位图

android - 使用我的 Android 应用程序中的 Oauth 在 Twitter 中的 CALLBACK_URL 上放置什么?

actionscript-3 - 在 Flex 中,如何创建、填充和显示位图?

java - 如果字符串包含双引号,则搜索 SQLite 表

c - AVSubtitleRect DVBSub格式解释

java - 将位图从相机保存到手机需要 25 秒以上

Android PNG 到位图 --- SkImageDecoder::Factory 返回 null

android - 如何通过 Robolectric 以编程方式获取自定义主题值

android - LogCat 消息 : The Google Play services resources were not found