在网上调查了图片压缩的方法并实装后,大致上可以认为有两类压缩:质量压缩(不改变图片的尺寸)和尺寸压缩(相当于是像素上的压缩);质量压缩一般可用于上传大图前的处理,这样就可以节省一定的流量,毕竟现在的手机拍照都能达到3M左右了,尺寸压缩一般可用于生成缩略图。
两种方法都实装在了我的项目中,结果却发现在质量压缩的模块中,本来1.9M的图片压缩后反而变成3M多了,很是奇怪,再做了进一步调查终于知道原因了。下面这个博客说的比较清晰:
android图片压缩总结
总结来看,图片有三种存在形式:硬盘上时是file,网络传输时是stream,内存中是stream或bitmap,所谓的质量压缩,它其实只能实现对file的影响,你可以把一个file转成bitmap再转成file,或者直接将一个bitmap转成file时,这个最终的file是被压缩过的,但是中间的bitmap并没有被压缩(或者说几乎没有被压缩,我不确定),因为bigmap在内存中的大小是按像素计算的,也就是width * height,对于质量压缩,并不会改变图片的像素,所以就算质量被压缩了,但是bitmap在内存的占有率还是没变小,但你做成file时,它确实变小了;
而尺寸压缩由于是减小了图片的像素,所以它直接对bitmap产生了影响,当然最终的file也是相对的变小了;
最后把自己总结的工具类贴出来:
package com.example.superdemo.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by Administrator on 2016/9/20.
* 图片压缩工具类
*/
public class ImageFactory {
/**
* Get bitmap from specified image path
*
* @param imgPath 文件路径
* @return Bitmap
*/
public Bitmap getBitmap(String imgPath) {
// Get bitmap through image path
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = false;
newOpts.inPurgeable = true;
newOpts.inInputShareable = true;
// Do not compress
newOpts.inSampleSize = 1;
newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
return BitmapFactory.decodeFile(imgPath, newOpts);
}
/**
* Store bitmap into specified image path
*
* @param bitmap
* @param outPath
* @throws FileNotFoundException
*/
public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {
FileOutputStream os = new FileOutputStream(outPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
}
/**
* Compress image by pixel, this will modify image width/height.
* Used to get thumbnail
* 尺寸压缩
* @param imgPath image path
* @param pixelW target pixel of width
* @param pixelH target pixel of height
* @return Bitmap
*/
public Bitmap ratio(String imgPath, float pixelW, float pixelH) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 开始读入图片,此时把options.inJustDecodeBounds 设回true,即只读边不读内容
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
// Get bitmap info, but notice that bitmap is null now
Bitmap bitmap = BitmapFactory.decodeFile(imgPath,newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// 想要缩放的目标尺寸
float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了
float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了
// 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) be = 1;
newOpts.inSampleSize = be;//设置缩放比例
// 开始压缩图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
// 压缩好比例大小后再进行质量压缩
// return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除
return bitmap;
}
/**
* Compress image by size, this will modify image width/height.
* Used to get thumbnail
*
* @param image
* @param pixelW target pixel of width
* @param pixelH target pixel of height
* @return
*/
public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, os);
if( os.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
os.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 50, os);//这里压缩50%,把压缩后的数据存放到baos中
}
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了
float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) be = 1;
newOpts.inSampleSize = be;//设置缩放比例
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
is = new ByteArrayInputStream(os.toByteArray());
bitmap = BitmapFactory.decodeStream(is, null, newOpts);
//压缩好比例大小后再进行质量压缩
// return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除
return bitmap;
}
/**
* Compress by quality, and generate image to the path specified
*
* @param image
* @param outPath
* @param maxSize target will be compressed to be smaller than this size.(kb)
* @throws IOException
*/
public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// scale
int options = 100;
// Store the bitmap into output stream(no compress)
image.compress(Bitmap.CompressFormat.JPEG, options, os);
// Compress by loop
while ( os.toByteArray().length / 1024 > maxSize) {
// Clean up os
os.reset();
// interval 10
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, os);
}
// Generate compressed image file
FileOutputStream fos = new FileOutputStream(outPath);
fos.write(os.toByteArray());
fos.flush();
fos.close();
}
/**
* Compress by quality, and generate image to the path specified
*
* @param imgPath
* @param outPath
* @param maxSize target will be compressed to be smaller than this size.(kb)
* @param needsDelete Whether delete original file after compress
* @throws IOException
*/
public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException {
compressAndGenImage(getBitmap(imgPath), outPath, maxSize);
// Delete original file
if (needsDelete) {
File file = new File (imgPath);
if (file.exists()) {
file.delete();
}
}
}
/**
* Ratio and generate thumb to the path specified
*
* @param image
* @param outPath
* @param pixelW target pixel of width
* @param pixelH target pixel of height
* @throws FileNotFoundException
*/
public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException {
Bitmap bitmap = ratio(image, pixelW, pixelH);
storeImage( bitmap, outPath);
}
/**
* Ratio and generate thumb to the path specified
*
* @param imgPath
* @param outPath
* @param pixelW target pixel of width
* @param pixelH target pixel of height
* @param needsDelete Whether delete original file after compress
* @throws FileNotFoundException
*/
public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException {
Bitmap bitmap = ratio(imgPath, pixelW, pixelH);
storeImage( bitmap, outPath);
// Delete original file
if (needsDelete) {
File file = new File (imgPath);
if (file.exists()) {
file.delete();
}
}
}
}
延伸阅读
android图片压缩总结
一.图片的存在形式
1.文件形式(即以二进制形式存在于硬盘上)
2.流的形式(即以二进制形式存在于内存中)
3.Bitmap形式
这三种形式的区别: 文件形式和流的形式对图片体积大小并没有影响,也就是说,如果你手机SD卡上的如果是100K,那么通过流的形式读到内存中,也一定是占100K的内存,注意是流的形式,不是Bitmap的形式,当图片以Bitmap的形式存在时,其占用的内存会瞬间变大, 我试过500K文件形式的图片加载到内存,以Bitmap形式存在时,占用内存将近10M,当然这个增大的倍数并不是固定的
检测图片三种形式大小的方法:
文件形式: file.length()
流的形式: 讲图片文件读到内存输入流中,看它的byte数
Bitmap: bitmap.getByteCount()
二.常见的压缩方式
1.将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,
特点是: File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变
public static void compressBmpToFile(Bitmap bmp,File file){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 80;//个人喜欢从80开始,
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
options -= 10;
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();
}
}
方法说明: 该方法是压缩图片的质量, 注意它不会减少图片的像素,比方说, 你的图片是300K的, 1280*700像素的, 经过该方法压缩后, File形式的图片是在100以下, 以方便上传服务器, 但是你BitmapFactory.decodeFile到内存中,变成Bitmap时,它的像素仍然是1280*700, 计算图片像素的方法是 bitmap.getWidth()和bitmap.getHeight(), 图片是由像素组成的, 每个像素又包含什么呢? 熟悉PS的人知道, 图片是有色相,明度和饱和度构成的.
该方法的官方文档也解释说, 它会让图片重新构造, 但是有可能图像的位深(即色深)和每个像素的透明度会变化,JPEG onlysupports opaque(不透明), 也就是说以jpeg格式压缩后, 原来图片中透明的元素将消失.所以这种格式很可能造成失真
既然它是改变了图片的显示质量, 达到了对File形式的图片进行压缩, 图片的像素没有改变的话, 那重新读取经过压缩的file为Bitmap时, 它占用的内存并不会少.(不相信的可以试试)
因为: bitmap.getByteCount() 是计算它的像素所占用的内存, 请看官方解释: Returns the number of bytes used to store this bitmap’s pixels.
2.将图片从本地读到内存时,进行压缩 ,即图片从File形式变为Bitmap形式
特点: 通过设置采样率, 减少图片的像素, 达到对内存中的Bitmap进行压缩
先看一个方法: 该方法是对内存中的Bitmap进行质量上的压缩, 由上面的理论可以得出该方法是无效的, 而且也是没有必要的,因为你已经将它读到内存中了,再压缩多此一举, 尽管在获取系统相册图片时,某些手机会直接返回一个Bitmap,但是这种情况下, 返回的Bitmap都是经过压缩的, 它不可能直接返回一个原声的Bitmap形式的图片, 后果可想而知
private Bitmap compressBmpFromBmp(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 100;
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
再看一个方法:
private Bitmap compressImageFromFile(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;//只读边,不读内容
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = 800f;//
float ww = 480f;//
int be = 1;
if (w > h && w > ww) {
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置采样率
newOpts.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设
newOpts.inPurgeable = true;// 同时设置才会有效
newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
// return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
//其实是无效的,大家尽管尝试
return bitmap;
}
方法说明: 该方法就是对Bitmap形式的图片进行压缩, 也就是通过设置采样率, 减少Bitmap的像素, 从而减少了它所占用的内存
分享个按照图片尺寸压缩:
public static void compressPicture(String srcPath, String desPath) {
FileOutputStream fos = null;
BitmapFactory.Options op = new BitmapFactory.Options();
// 开始读入图片,此时把options.inJustDecodeBounds 设回true了
op.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, op);
op.inJustDecodeBounds = false;
// 缩放图片的尺寸
float w = op.outWidth;
float h = op.outHeight;
float hh = 1024f;//
float ww = 1024f;//
// 最长宽度或高度1024
float be = 1.0f;
if (w > h && w > ww) {
be = (float) (w / ww);
} else if (w < h && h > hh) {
be = (float) (h / hh);
}
if (be <= 0) {
be = 1.0f;
}
op.inSampleSize = (int) be;// 设置缩放比例,这个数字越大,图片大小越小.
// 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, op);
int desWidth = (int) (w / be);
int desHeight = (int) (h / be);
bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
try {
fos = new FileOutputStream(desPath);
if (bitmap != null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
需要注意两个问题:
一、调用getDrawingCache()前先要测量,否则的话得到的bitmap为null,这个我在OnCreate()、OnStart()、OnResume()方法里都试验过。
二、当调用bitmap.compress(CompressFormat.JPEG, 100, fos);保存为图片时发现图片背景为黑色
这时只需要改成用png保存就可以了,bitmap.compress(CompressFormat.PNG, 100, fos);,如下图:
/*
压缩图片,处理某些手机拍照角度旋转的问题
*/
public static String compressImage(Context context,String filePath,String fileName,int q) throws FileNotFoundException {
Bitmap bm = getSmallBitmap(filePath);
int degree = readPictureDegree(filePath);
if(degree!=0){//旋转照片角度
bm=rotateBitmap(bm,degree);
}
File imageDir = SDCardUtils.getImageDir(context);
File outputFile=new File(imageDir,fileName);
FileOutputStream out = new FileOutputStream(outputFile);
bm.compress(Bitmap.CompressFormat.JPEG, q, out);
return outputFile.getPath();
}
判断照片角度
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
旋转照片
public static Bitmap rotateBitmap(Bitmap bitmap,int degress) {
if (bitmap != null) {
Matrix m = new Matrix();
m.postRotate(degress);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
return bitmap;
}
return bitmap;
}
指定分辨率和清晰度的图片压缩方法
public void transImage(String fromFile, String toFile, int width, int height, int quality)
{
try
{
Bitmap bitmap = BitmapFactory.decodeFile(fromFile);
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
// 缩放图片的尺寸
float scaleWidth = (float) width / bitmapWidth;
float scaleHeight = (float) height / bitmapHeight;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 产生缩放后的Bitmap对象
Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
// save file
File myCaptureFile = new File(toFile);
FileOutputStream out = new FileOutputStream(myCaptureFile);
if(resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)){
out.flush();
out.close();
}
if(!bitmap.isRecycled()){
bitmap.recycle();//记得释放资源,否则会内存溢出
}
if(!resizeBitmap.isRecycled()){
resizeBitmap.recycle();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
Android编程之Bitmap图片压缩大小
这里所谓的缩小尺寸可不是指在layout中设置一下宽高使图片缩小(其实质还是一张占内存大图),而是实实在在的将图片本身缩小,减小内存占用。
以下是方法,详细说明都在注释里了:
private Bitmap revitionImageSize(String path, int size) throws IOException {
// 取得图片
InputStream temp = this.getAssets().open(path);
BitmapFactory.Options options = new BitmapFactory.Options();
// 这个参数代表,不为bitmap分配内存空间,只记录一些该图片的信息(例如图片大小),说白了就是为了内存优化
options.inJustDecodeBounds = true;
// 通过创建图片的方式,取得options的内容(这里就是利用了java的地址传递来赋值)
BitmapFactory.decodeStream(temp, null, options);
// 关闭流
temp.close();
// 生成压缩的图片
int i = 0;
Bitmap bitmap = null;
while (true) {
// 这一步是根据要设置的大小,使宽和高都能满足
if ((options.outWidth >> i <= size)
&& (options.outHeight >> i <= size)) {
// 重新取得流,注意:这里一定要再次加载,不能二次使用之前的流!
temp = this.getAssets().open(path);
// 这个参数表示 新生成的图片为原始图片的几分之一。
options.inSampleSize = (int) Math.pow(2.0D, i);
// 这里之前设置为了true,所以要改为false,否则就创建不出图片
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(temp, null, options);
break;
}
i += 1;
}
return bitmap;
Q:加载时图片时有一些图片太大,导致内存溢出,想把这些图片压缩成一个缩略图,该怎么做?
不能只是缩小图片大小,而是要把体积降下来,几百K的图片压缩成几K或几百B.
A1:
压缩图片质量:
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
其中的quality为0~100, 可以压缩图片质量, 不过对于大图必须对图片resize
这个是等比例缩放:
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
newBitmap = Bitmap.createBitmap(oldBitmap, 0, 0, width, height, matrix, true);//用距阵的方式缩放
这个是截取图片某部分:
bitmap = Bitmap.createBitmap(bitmap, x, y, width, height);
这几个方法都是针对Bitmap的, 不过鉴于Bitmap可以从file中读取, 也可以写入file.
这是我知道Android自带库里中唯一可以缩放和压缩的图片方法.
第一种方法--及时回收bitmap内存:
一般而言,回收bitmap内存可以用到以下代码
if(bitmap != null && !bitmap.isRecycled()){
bitmap.recycle();
bitmap = null;
}
System.gc();
第二种方法–压缩图片:
这个方法当然很简单了,就是使图片体积大小变小,
可以有两种方式:
一种是使图片质量降低(分辨率不变),
另一种是使图片分辨率降低(分辨率改变)。
总之,使图片大小变小就行了。
实践证明,使图片质量降低(分辨率不变)可以大幅度地减小体积,而且质量的差异肉眼看上去并不明显、
/压缩,用于节省BITMAP内存空间--解决BUG的关键步骤
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2; //这个的值压缩的倍数(2的整数倍),数值越小,压缩率越小,图片越清晰
//返回原图解码之后的bitmap对象
bitmap = BitmapFactory.decodeResource(Context, ResourcesId, opts);
即先将图片缩小一倍,再将这缩小了一倍的图片作为bitmap存入内存,这样一来,它占用的bitmap内存大大减小。