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

使用Android压缩像Whatsapp和Facebook这样的图像,android,image,facebook,compression,whatsapp,Android,Image,Facebook,Compression,Whatsapp,我已经试过用这段代码来转换图像对于标题位大小来说效果不错,但是我想调整图像动态的大小,比如Whatsapp和Facebook。 在Whatsapp4到5 MB中,图像被压缩到KB中,那么我该怎么做呢 public String compressImage(String imageUri) { String filePath = getRealPathFromURI(imageUri); Bitmap scaledBitmap = null; BitmapFactor

我已经试过用这段代码来转换
图像
对于标题位大小来说效果不错,但是我想调整图像动态的大小,比如Whatsapp和Facebook。 在
Whatsapp
4
5 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;
}
公共字符串压缩图像(字符串图像URI){
字符串filePath=getRealPathFromURI(imageUri);
位图缩放位图=空;
BitmapFactory.Options=new-BitmapFactory.Options();
options.inJustDecodeBounds=true;
位图bmp=BitmapFactory.decodeFile(文件路径,选项);
int实际高度=options.outHeight;
int actualWidth=options.outWidth;
浮动最大高度=816.0f;
浮动最大宽度=612.0f;
浮动高度=实际宽度/实际高度;
浮点最大比值=最大宽度/最大高度;
如果(实际高度>最大高度| |实际宽度>最大宽度){
if(imgRatiomaxRatio){
imgRatio=最大宽度/实际宽度;
实际高度=(int)(imgRatio*实际高度);
实际宽度=(int)最大宽度;
}否则{
实际高度=(int)最大高度;
实际宽度=(int)最大宽度;
}
}
options.inSampleSize=calculateInSampleSize(选项、实际宽度、实际高度);
options.inpurgable=true;
options.inInputShareable=true;
options.inTempStorage=新字节[16*1024];
试一试{
bmp=BitmapFactory.decodeFile(文件路径,选项);
}捕获(OutOfMemoryError异常){
异常。printStackTrace();
}
试一试{
scaledbimat=Bitmap.createBitmap(实际宽度、实际高度、Bitmap.Config.ARGB_8888);
}捕获(OutOfMemoryError异常){
异常。printStackTrace();
}
浮动比率=实际宽度/(浮动)选项。向外宽度;
浮动比率=实际高度/(浮动)选项。超出高度;
浮动中间点x=实际宽度/2.0f;
浮动中间Y=实际高度/2.0f;
矩阵scaleMatrix=新矩阵();
scaleMatrix.setScale(ratioX、ratioY、middleX、middleY);
画布画布=新画布(缩放位图);
canvas.setMatrix(scaleMatrix);
drawBitmap(bmp,middleX-bmp.getWidth()/2,middleY-bmp.getHeight()/2,新绘制(Paint.FILTER_位图_标志));
出口接口;
试一试{
exif=新的ExifInterface(文件路径);
int-orientation=exif.getAttributeInt(
ExiFinInterface.TAG_方向,0);
Log.d(“EXIF”,“EXIF:+方向”);
矩阵=新矩阵();
如果(方向==6){
矩阵旋转后(90);
Log.d(“EXIF”,“EXIF:+方向”);
}否则如果(方向==3){
矩阵旋转后(180);
Log.d(“EXIF”,“EXIF:+方向”);
}否则如果(方向==8){
矩阵旋转后(270);
Log.d(“EXIF”,“EXIF:+方向”);
}
scaledBitmap=Bitmap.createBitmap(scaledBitmap,0,0,
scaledBitmap.getWidth(),scaledBitmap.getHeight(),矩阵,
正确的);
}捕获(IOE异常){
e、 printStackTrace();
}
FileOutputStream out=null;
字符串filename=getFilename();
试一试{
out=新文件输出流(文件名);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG,80,out);
}catch(filenotfounde异常){
e、 printStackTrace();
}
返回文件名;
}
公共字符串getFilename(){
File File=新文件(Environment.getExternalStorageDirectory().getPath(),“MyFolder/Images”);
如果(!file.exists()){
mkdirs()文件;
}
字符串uriSting=(file.getAbsolutePath()+“/”+System.currentTimeMillis()+”.jpg”);
回归分析;
}
私有字符串getRealPathFromURI(字符串contentURI){
uricontenturi=Uri.parse(contentUri);
Cursor Cursor=getContentResolver().query(contentUri,null,null,null);
if(游标==null){
返回contentUri.getPath();
}否则{
cursor.moveToFirst();
int index=cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
返回cursor.getString(索引);
}
}
公共int-calculateInSampleSize(BitmapFactory.Options选项、int-reqWidth、int-reqHeight){
最终内部高度=options.outHeight;
最终整数宽度=options.outWidth;
int inSampleSize=1;
如果(高度>要求高度| |宽度>要求宽度){
最终内部高度比=数学圆((浮动)高度/(浮动)要求高度);
最终整数宽度比=数学圆((浮动)宽度/(浮动)宽度);
inSampleSize=heightRatiototalReqPixelsCap){
inSampleSize++;
}
返回样本大小;
}
此代码用于转换图像,但在我的项目要求中是这样的。

  • 对于裁剪图像,可以使用以下命令

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

    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);
    }
    
    公共位图解码文件(字符串文件路径){
    BitmapFactory.Options o=新的BitmapFactory.Options();
    o、 inJustDecodeBounds=true;
    解码文件(文件路径,o);
    //我们要扩展到的新尺寸
    所需的最终int_SIZE=1024;
    //找到正确的刻度值。它应该是2的幂。
    内部宽度=o.向外宽度,高度=o.向外高度;
    int标度=1;
    while(true){
    如果(宽度\u tmp<要求的\u尺寸和高度\u tmp<要求的\u尺寸)
    打破
    宽度_tmp/=2;
    高度_tmp/=2;
    比例*=2;
    }
    //用inSampleSize解码
    BitmapFactory.Options o2=新的BitmapFactory.Options();
    o2.inSampleSize=刻度;
    位图图像=BitmapFactory.decod