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



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

我只知道使用

  • BitmapFactory。减少大小和质量的选项

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

公共位图压缩图像(字符串imagePath){

    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*1000px的图像。您要将图像转换为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/原始尺寸(278):1024 768 12-07

17:43:36.333:E/压缩尺寸(278):1024 768

public static int getSquareCropDimensionForBitmap(Bitmap bitmap)
{
    int dimension;
    //If the bitmap is wider than it is tall
    //use the height as the square crop dimension
    if (bitmap.getWidth() >= bitmap.getHeight())
    {
        dimension = bitmap.getHeight();
    }
    //If the bitmap is taller than it is wide
    //use the width as the square crop dimension
    else
    {
        dimension = bitmap.getWidth();
    }
return  dimension;
}

int dimension=getSquareCropDimensionForBitmap(位图);

        System.out.println("before cropped height " + bitmap.getHeight() + "and width: " + bitmap.getWidth());
        Bitmap croppedBitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
        System.out.println("after cropped height "+croppedBitmap.getHeight() +"and width: " + croppedBitmap.getWidth());

它可以裁剪并缩小大小u可以指定自己的大小

最新更新