一、质量压缩(图片文件大小压缩)
压缩后加载成bitmap占用内存不会变,SD卡中存储大小变小
Bimap 中compress(Bitmap.CompressFormat format,int option,Outputstream outStream)方法三个参数
1、format------压缩后图片的格式Bitmap.CompressFormat .JPEG、.PNG、.WEBP。
2、option(0-100)值越小图片失真越大,压缩后所占内存越少
3、outStream压缩后输入位置
- public static void compressBmpToFile(Bitmap bmp,File file){
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- int options = 100;//
- bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
- while (baos.toByteArray().length / 1024 > 100) {
- baos.reset();
- options -= 5;
- bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
- }
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(baos.toByteArray());
- fos.flush();
- fos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
二、尺寸压缩(bitmap像素的压缩)
原理就是先加载图片的宽高而不加载图片的内容,根据图片要显示控件的宽高计算压缩后图片的宽高
用BitmapFactory.decodeFile(filePath, options)从新加载生成图片,参数filePath算图片的路径,options图片像素大小等相关属性。
这里尺寸压缩也就是常说的二次采样,
- /**
- * @param filePath 要加载的图片路径
- * @param destWidth 显示图片的控件宽度
- * @param destHeight 显示图片的控件的高度
- * @return
- */
- public static Bitmap decodeBitmap(String filePath, int destWidth, int destHeight) {
- //第一次采样
- BitmapFactory.Options options = new BitmapFactory.Options();
- //该属性设置为true只会加载图片的边框进来,并不会加载图片具体的像素点
- options.inJustDecodeBounds = true;
- //第一次加载图片,这时只会加载图片的边框进来,并不会加载图片中的像素点
- BitmapFactory.decodeFile(filePath, options);
- //获得原图的宽和高
- int outWidth = options.outWidth;
- int outHeight = options.outHeight;
- //定义缩放比例
- int sampleSize = 1;
- while (outHeight / sampleSize > destHeight || outWidth / sampleSize > destWidth) {
- //如果宽高的任意一方的缩放比例没有达到要求,都继续增大缩放比例
- //sampleSize应该为2的n次幂,如果给sampleSize设置的数字不是2的n次幂,那么系统会就近取值
- sampleSize *= 2;
- }
- /********************************************************************************************/
- //至此,第一次采样已经结束,我们已经成功的计算出了sampleSize的大小
- /********************************************************************************************/
- //二次采样开始
- //二次采样时我需要将图片加载出来显示,不能只加载图片的框架,因此inJustDecodeBounds属性要设置为false
- options.inJustDecodeBounds = false;
- //设置缩放比例
- options.inSampleSize = sampleSize;
- options.inPreferredConfig = Bitmap.Config.ARGB_8888;
- //加载图片并返回
- return BitmapFactory.decodeFile(filePath, options);
- }