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

时间:2016-01-13 13:49:13

标签: android bitmap bitmapfactory

有没有办法可以在Android中强化115kb的图像为4kb 而不影响它的大小?。只是降低它的质量?

我只知道使用

  • BitmapFactory.Options减少了尺寸和质量

  • Bitmap.compress没有为您提供指定大小的选项。

public Bitmap compressImage(String 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;
}

2 个答案:

答案 0 :(得分:0)

图像尺寸调整意味着您将缩短图像的分辨率。假设用户选择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 /原始尺寸(278):1024 768 12-07

     

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

答案 1 :(得分:0)

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

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

它可以裁剪并且可以减小尺寸你可以指定你自己的尺寸