Android 图片压缩,基于比例和质量压缩

packagecc.util.android.image;
 
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.math.BigDecimal;
importjava.math.RoundingMode;
importjava.nio.ByteBuffer;
importjava.nio.channels.Channels;
importjava.nio.channels.ReadableByteChannel;
importandroid.content.Context;
importandroid.content.res.Resources;
importandroid.graphics.Bitmap;
importandroid.graphics.Bitmap.CompressFormat;
importandroid.graphics.BitmapFactory;
importandroid.graphics.BitmapFactory.Options;
importandroid.graphics.Matrix;
importandroid.media.ExifInterface;
importandroid.util.Log;
 
/**
 * A class for helping deal the bitmap,
 *  like: get the orientation of the bitmap, compress bitmap etc.
 * @author wangcccong
 * @version 1.140122
 * crated at: 2014-03-22
 * update at: 2014-06-26
 */
publicclass BitmapHelper {
 
    /**
     * get the orientation of the bitmap {@link android.media.ExifInterface}
     * @param path
     * @return
     */
    publicfinal static int getDegress(String path) {
        intdegree = 0;
        try{
            ExifInterface exifInterface = newExifInterface(path);
            intorientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch(orientation) {
            caseExifInterface.ORIENTATION_ROTATE_90:
                degree = 90;
                break;
            caseExifInterface.ORIENTATION_ROTATE_180:
                degree = 180;
                break;
            caseExifInterface.ORIENTATION_ROTATE_270:
                degree = 270;
                break;
            }
        }catch(IOException e) {
            e.printStackTrace();
        }
        returndegree;
    }
     
    /**
     * rotate the bitmap 
     * @param bitmap
     * @param degress
     * @return
     */
    publicstatic Bitmap rotateBitmap(Bitmap bitmap, intdegress) {
        if(bitmap != null) {
            Matrix m = newMatrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0,0, bitmap.getWidth(), bitmap.getHeight(), m, true);
            returnbitmap;
        }
        returnbitmap;
    }
     
    /**
     * caculate the bitmap sampleSize
     * @param path
     * @return
     */
    publicfinal static int caculateInSampleSize(BitmapFactory.Options options, intrqsW, intrqsH) {
        finalint height = options.outHeight;
        finalint width = options.outWidth;
        intinSampleSize = 1;
        if(rqsW == 0|| rqsH == 0)return1;
        if(height > rqsH || width > rqsW) {
            finalint heightRatio = Math.round((float) height/ (float) rqsH);
            finalint widthRatio = Math.round((float) width / (float) rqsW);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        returninSampleSize;
    }
     
    /**
     * 压缩指定路径的图片,并得到图片对象
     * @param context
     * @param path bitmap source path
     * @return Bitmap {@link android.graphics.Bitmap}
     */
    publicfinal static Bitmap compressBitmap(String path, intrqsW, intrqsH) {
        finalBitmapFactory.Options options = newBitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = caculateInSampleSize(options, rqsW, rqsH);
        options.inJustDecodeBounds = false;
        returnBitmapFactory.decodeFile(path, options);
    }
     
    /**
     * 压缩指定路径图片,并将其保存在缓存目录中,通过isDelSrc判定是否删除源文件,并获取到缓存后的图片路径
     * @param context
     * @param srcPath
     * @param rqsW
     * @param rqsH
     * @param isDelSrc
     * @return
     */
    publicfinal static String compressBitmap(Context context, String srcPath, intrqsW, intrqsH, booleanisDelSrc) {
        Bitmap bitmap = compressBitmap(srcPath, rqsW, rqsH);
        File srcFile = newFile(srcPath);
        String desPath = getImageCacheDir(context) + srcFile.getName();
        intdegree = getDegress(srcPath);
        try{
            if(degree != 0) bitmap = rotateBitmap(bitmap, degree);
            File file = newFile(desPath);
            FileOutputStream  fos = newFileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG,70, fos);
            fos.close();
            if(isDelSrc) srcFile.deleteOnExit();
        }catch(Exception e) {
            // TODO: handle exception
            Log.e("BitmapHelper-->compressBitmap", e.getMessage()+"");
        }
        returndesPath;
    }
     
    /**
     * 此方法过期,该方法可能造成OutOfMemoryError,使用不含isAdjust参数的方法
     * @param is
     * @param reqsW
     * @param reqsH
     * @param isAdjust
     * @return
     */
    @Deprecated
    publicfinal static Bitmap compressBitmap(InputStream is, intreqsW, intreqsH, booleanisAdjust) {
        Bitmap bitmap = BitmapFactory.decodeStream(is);
        returncompressBitmap(bitmap, reqsW, reqsH, isAdjust);
    }
     
    /**
     * 压缩某个输入流中的图片,可以解决网络输入流压缩问题,并得到图片对象
     * @param context
     * @param path bitmap source path
     * @return Bitmap {@link android.graphics.Bitmap}
     */
    publicfinal static Bitmap compressBitmap(InputStream is, intreqsW, intreqsH) {
        try{
            ByteArrayOutputStream baos = newByteArrayOutputStream();
            ReadableByteChannel channel = Channels.newChannel(is);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while(channel.read(buffer) != -1) {
                buffer.flip();
                while(buffer.hasRemaining()) baos.write(buffer.get());
                buffer.clear();
            }
            byte[] bts = baos.toByteArray();
            Bitmap bitmap = compressBitmap(bts, reqsW, reqsH);
            is.close();
            channel.close();
            baos.close();
            returnbitmap;
        }catch(Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            returnnull;
        }
    }
     
    /**
     * 压缩指定byte[]图片,并得到压缩后的图像
     * @param bts
     * @param reqsW
     * @param reqsH
     * @return
     */
    publicfinal static Bitmap compressBitmap(byte[] bts, intreqsW, intreqsH) {
        finalOptions options = newOptions();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bts,0, bts.length, options);
        options.inSampleSize = caculateInSampleSize(options, reqsW, reqsH);
        options.inJustDecodeBounds = false;
        returnBitmapFactory.decodeByteArray(bts, 0, bts.length, options);
    }
     
    /**
     * 此方法已过期,该方法可能造成OutOfMemoryError,使用不含isAdjust参数的方法
     * @param bitmap
     * @param reqsW
     * @param reqsH
     * @return
     */
    @Deprecated
    publicfinal static Bitmap compressBitmap(Bitmap bitmap, intreqsW, intreqsH, booleanisAdjust) {
        if(bitmap == null|| reqsW == 0|| reqsH == 0)returnbitmap;
        if(bitmap.getWidth() > reqsW || bitmap.getHeight() > reqsH) {
            floatscaleX = newBigDecimal(reqsW).divide(newBigDecimal(bitmap.getWidth()), 4, RoundingMode.DOWN).floatValue();
            floatscaleY = newBigDecimal(reqsH).divide(newBigDecimal(bitmap.getHeight()), 4, RoundingMode.DOWN).floatValue();
            if(isAdjust) {
                scaleX = scaleX < scaleY ? scaleX : scaleY;
                scaleY = scaleX;
            }
            Matrix matrix = newMatrix();
            matrix.postScale(scaleX, scaleY);
            bitmap = Bitmap.createBitmap(bitmap, 0,0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }
        returnbitmap;
    }
     
    /**
     * 压缩已存在的图片对象,并返回压缩后的图片
     * @param bitmap
     * @param reqsW
     * @param reqsH
     * @return
     */
    publicfinal static Bitmap compressBitmap(Bitmap bitmap, intreqsW, intreqsH) {
        try{
            ByteArrayOutputStream baos = newByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG,100, baos);
            byte[] bts = baos.toByteArray();
            Bitmap res = compressBitmap(bts, reqsW, reqsH);
            baos.close();
            returnres;
        }catch(IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            returnbitmap;
        }
    }
     
    /**
     * 此方法过期,该方法可能造成OutOfMemoryError,使用不含isAdjust参数的方法
     * get bitmap form resource dictory, and then compress bitmap according to reqsW and reqsH
     * @param res {@link android.content.res.Resources}
     * @param resID
     * @param reqsW
     * @param reqsH
     * @return
     */
    @Deprecated
    publicfinal static Bitmap compressBitmap(Resources res, intresID, intreqsW, intreqsH, booleanisAdjust) {
        Bitmap bitmap = BitmapFactory.decodeResource(res, resID);
        returncompressBitmap(bitmap, reqsW, reqsH, isAdjust);
    }
     
    /**
     * 压缩资源图片,并返回图片对象
     * @param res {@link android.content.res.Resources}
     * @param resID
     * @param reqsW
     * @param reqsH
     * @return
     */
    publicfinal static Bitmap compressBitmap(Resources res, intresID, intreqsW, intreqsH) {
        finalOptions options = newOptions();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resID, options);
        options.inSampleSize = caculateInSampleSize(options, reqsW, reqsH);
        options.inJustDecodeBounds = false;
        returnBitmapFactory.decodeResource(res, resID, options);
    }
     
     
     
    /**
     * 基于质量的压缩算法, 此方法未 解决压缩后图像失真问题
     * <br> 可先调用比例压缩适当压缩图片后,再调用此方法可解决上述问题
     * @param bts
     * @param maxBytes 压缩后的图像最大大小 单位为byte
     * @return
     */
    publicfinal static Bitmap compressBitmap(Bitmap bitmap, longmaxBytes) {
        try{
            ByteArrayOutputStream baos = newByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG,100, baos);
            intoptions = 90;
            while(baos.toByteArray().length > maxBytes) {
                baos.reset();
                bitmap.compress(CompressFormat.PNG, options, baos);
                options -= 10;
            }
            byte[] bts = baos.toByteArray();
            Bitmap bmp = BitmapFactory.decodeByteArray(bts, 0, bts.length);
            baos.close();
            returnbmp;
        }catch(IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            returnnull;
        }
    }
     
//  public final static Bitmap compressBitmap(InputStream is, long maxBytes) {
//      try {
//          ByteArrayOutputStream baos = new ByteArrayOutputStream();
//          byte[] bts = new byte[1024];
//          while (is.read(bts) != -1) baos.write(bts, 0, bts.length);
//          is.close();
//          int options = 100;
//          while (baos.toByteArray().length > maxBytes) {
//             
//          }
//      } catch (Exception e) {
//          // TODO: handle exception
//      }
//  }
     
    /**
     * 得到指定路径图片的options
     * @param srcPath
     * @return Options {@link android.graphics.BitmapFactory.Options}
     */
    publicfinal static Options getBitmapOptions(String srcPath) {
        BitmapFactory.Options options = newBitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(srcPath, options);
        returnoptions;
    }
     
    /**
     * 获取图片缓存路径
     * @param context
     * @return
     */
    privatestatic String getImageCacheDir(Context context) {
        String dir = FileHelper.getCacheDir(context) + "Image"+ File.separator;
        File file = newFile(dir);
        if(!file.exists()) file.mkdirs();
        returndir;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值