bitmap 质量压缩并保存到本地

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_28864443/article/details/83184550
/**
* 质量压缩方法
*
* @param image
* @return
*/
public static Bitmap compressImage(Bitmap image) {

ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 90;

while (baos.toByteArray().length / 1024 > 800) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset(); // 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//
// 这里压缩options%,把压缩后的数据存放到baos中
if (options > 10) {//设置最小值,防止低于0时出异常
options -= 10;// 每次都减少10
}
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//
// 把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//
// 把ByteArrayInputStream数据生成图片
return bitmap;
}
/**
 * 保存bitmap到本地
 *
 * @param context
 * @param mBitmap
 * @return
 */
public static String saveBitmap(Context context, Bitmap mBitmap) {
    String savePath;
    File filePic;
    savePath = context.getApplicationContext().getFilesDir().getAbsolutePath();
    try {
        filePic = new File(savePath + "/image/map.jpg");
        if (!filePic.exists()) {
            filePic.getParentFile().mkdirs();
            filePic.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(filePic);
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (IOException e) { // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    return filePic.getAbsolutePath();
}

猜你喜欢

转载自blog.csdn.net/sinat_28864443/article/details/83184550