使用Android压缩像Whatsapp和Facebook的图像

时间:2015-05-20 09:27:17

标签: android image facebook compression whatsapp

我已尝试使用此代码转换image它的标题位大小正常工作,但我希望调整动态图像的大小,如Whatsapp和Facebook。 Whatsapp 45 MB图片中的图片会被压缩为KB,那该怎么办呢?

 public String compressImage(String imageUri) {

    String filePath = getRealPathFromURI(imageUri);
    Bitmap scaledBitmap = null;

    BitmapFactory.Options options = new BitmapFactory.Options();

    options.inJustDecodeBounds = true;
    Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

    int actualHeight = options.outHeight;
    int actualWidth = options.outWidth;

    float maxHeight = 816.0f;
    float maxWidth = 612.0f;
    float imgRatio = actualWidth / actualHeight;
    float maxRatio = maxWidth / maxHeight;

    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if (imgRatio < maxRatio) {               imgRatio = maxHeight /     actualHeight;                actualWidth = (int) (imgRatio * actualWidth);                   actualHeight = (int) maxHeight;             } else if (imgRatio > maxRatio) {
            imgRatio = maxWidth / actualWidth;
            actualHeight = (int) (imgRatio * actualHeight);
            actualWidth = (int) maxWidth;
        } else {
            actualHeight = (int) maxHeight;
            actualWidth = (int) maxWidth;

        }
    }

     options.inSampleSize = calculateInSampleSize(options, actualWidth,     actualHeight);

    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inTempStorage = new byte[16 * 1024];

    try {
         bmp = BitmapFactory.decodeFile(filePath, options);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();

    }
    try {
        scaledBitmap = Bitmap.createBitmap(actualWidth,     actualHeight,Bitmap.Config.ARGB_8888);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }

    float ratioX = actualWidth / (float) options.outWidth;
    float ratioY = actualHeight / (float) options.outHeight;
    float middleX = actualWidth / 2.0f;
    float middleY = actualHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY -     bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

     ExifInterface exif;
    try {
        exif = new ExifInterface(filePath);

        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION, 0);
        Log.d("EXIF", "Exif: " + orientation);
        Matrix matrix = new Matrix();
        if (orientation == 6) {
            matrix.postRotate(90);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 3) {
            matrix.postRotate(180);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 8) {
            matrix.postRotate(270);
            Log.d("EXIF", "Exif: " + orientation);
        }
        scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                true);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FileOutputStream out = null;
    String filename = getFilename();
    try {
        out = new FileOutputStream(filename);

       scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return filename;

}

public String getFilename() {
File file = new File(Environment.getExternalStorageDirectory().getPath(),     "MyFolder/Images");
if (!file.exists()) {
    file.mkdirs();
}
String uriSting = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");
return uriSting;

}

private String getRealPathFromURI(String contentURI) {
    Uri contentUri = Uri.parse(contentURI);
    Cursor cursor = getContentResolver().query(contentUri, null, null, null,     null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index =     cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(index);
    }
}
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;
}

此代码转换图像,但在我的项目要求中。

1 个答案:

答案 0 :(得分:1)

  • 对于裁剪图片,您可以使用此lib

  • 并且对于压缩图像,您也可以使用此代码。

    public Bitmap decodeFile(String filePath) {
    
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);
    
    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;
    
    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    
    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    Bitmap image = BitmapFactory.decodeFile(filePath, o2);
    
     ExifInterface exif;
        try 
        {               
            exif = new ExifInterface(filePath);
            int exifOrientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
    
            int rotate = 0;
            switch (exifOrientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;
    
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;
    
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
            }
    
            if (rotate != 0) {
                int w = image.getWidth();
                int h = image.getHeight();
    
                // Setting pre rotate
                Matrix mtx = new Matrix();
                mtx.preRotate(rotate);
    
                // Rotating Bitmap & convert to ARGB_8888, required by tess
                image = Bitmap.createBitmap(image, 0, 0, w, h, mtx, false);
    
            }
        } catch (IOException e) {
                 return null;
        }
        return image.copy(Bitmap.Config.ARGB_8888, true);
    }