当前位置: 移动技术网 > 移动技术>移动开发>Android > Android中图片压缩方案详解及源码下载

Android中图片压缩方案详解及源码下载

2019年07月24日  | 移动技术网移动技术  | 我要评论

android中图片压缩方案详解及源码下载

图片的展示可以说在我们任何一个应用中都避免不了,可是大量的图片就会出现很多的问题,比如加载大图片或者多图时的oom问题,可以移步到android高效加载大图及多图避免程序oom.还有一个问题就是图片的上传下载问题,往往我们都喜欢图片既清楚又占的内存小,也就是尽可能少的耗费我们的流量,这就是我今天所要讲述的问题:图片的压缩方案的详解。

1、质量压缩法

设置bitmap options属性,降低图片的质量,像素不会减少

第一个参数为需要压缩的bitmap图片对象,第二个参数为压缩后图片保存的位置

设置options 属性0-100,来实现压缩。

private bitmap compressimage(bitmap image) { 
 bytearrayoutputstream baos = new bytearrayoutputstream(); 
 image.compress(bitmap.compressformat.jpeg, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 
 int options = 100; 
 while ( baos.tobytearray().length / 1024>100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩 
 baos.reset();//重置baos即清空baos 
 image.compress(bitmap.compressformat.jpeg, options, baos);//这里压缩options%,把压缩后的数据存放到baos中 
 options -= 10;//每次都减少10 
 } 
 bytearrayinputstream isbm = new bytearrayinputstream(baos.tobytearray());//把压缩后的数据baos存放到bytearrayinputstream中 
 bitmap bitmap = bitmapfactory.decodestream(isbm, null, null);//把bytearrayinputstream数据生成图片 
 return bitmap; 
 }

质量压缩不会减少图片的像素。它是在保持像素不变的前提下改变图片的位深及透明度等,来达到压缩图片的目的。进过它压缩的图片文件大小会有改变,但是导入成bitmap后占得内存是不变的。因为要保持像素不变,所以它就无法无限压缩,到达一个值之后就不会继续变小了。显然这个方法并不适用于缩略图,其实也不适用于想通过压缩图片减少内存的适用,仅仅适用于想在保证图片质量的同时减少文件大小的情况而已。

2、采样率压缩法

private bitmap getimage(string srcpath) { 
 bitmapfactory.options newopts = new bitmapfactory.options(); 
 //开始读入图片,此时把options.injustdecodebounds 设回true了 
 newopts.injustdecodebounds = true; 
 bitmap bitmap = bitmapfactory.decodefile(srcpath,newopts);//此时返回bm为空 
 newopts.injustdecodebounds = false; 
 int w = newopts.outwidth; 
 int h = newopts.outheight; 
 //现在主流手机比较多是1280*720分辨率,所以高和宽我们设置为 
 float hh = 1280f;//这里设置高度为1280f 
 float ww = 720f;//这里设置宽度为720f 
 //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 
 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(srcpath, newopts); 
 return compressimage(bitmap);//压缩好比例大小后再进行质量压缩 
 }

这个方法的好处是大大的缩小了内存的使用,在读存储器上的图片时,如果不需要高清的效果,可以先只读取图片的边,通过宽和高设定好取样率后再加载图片,这样就不会过多的占用内存。

3、缩放法

通过缩放图片像素来减少图片占用内存大小。

方式一

public static void compressbitmaptofile(bitmap bmp, file file){
 // 尺寸压缩倍数,值越大,图片尺寸越小
 int ratio = 2;
 // 压缩bitmap到对应尺寸
 bitmap result = bitmap.createbitmap(bmp.getwidth() / ratio, bmp.getheight() / ratio, config.argb_8888);
 canvas canvas = new canvas(result);
 rect rect = new rect(0, 0, bmp.getwidth() / ratio, bmp.getheight() / ratio);
 canvas.drawbitmap(bmp, null, rect, null);

 bytearrayoutputstream baos = new bytearrayoutputstream();
 // 把压缩后的数据存放到baos中
 result.compress(bitmap.compressformat.jpeg, 100 ,baos);
 try { 
 fileoutputstream fos = new fileoutputstream(file); 
 fos.write(baos.tobytearray()); 
 fos.flush(); 
 fos.close(); 
 } catch (exception e) { 
 e.printstacktrace(); 
 } 
}

方式二

bytearrayoutputstream out = new bytearrayoutputstream(); 
image.compress(bitmap.compressformat.jpeg, 85, out); 
float zoom = (float)math.sqrt(size * 1024 / (float)out.tobytearray().length); 

matrix matrix = new matrix(); 
matrix.setscale(zoom, zoom); 

bitmap result = bitmap.createbitmap(image, 0, 0, image.getwidth(), image.getheight(), matrix, true); 

out.reset(); 
result.compress(bitmap.compressformat.jpeg, 85, out); 
while(out.tobytearray().length > size * 1024){ 
 system.out.println(out.tobytearray().length); 
 matrix.setscale(0.9f, 0.9f); 
 result = bitmap.createbitmap(result, 0, 0, result.getwidth(), result.getheight(), matrix, true); 
 out.reset(); 
 result.compress(bitmap.compressformat.jpeg, 85, out); 
}

缩放法其实很简单,设定好matrix,在createbitmap就可以了。但是我们并不知道缩放比例,而是要求了图片的最终大小。直接用大小的比例来做的话肯定是有问题的,用大小比例的开方来做会比较接近,但是还是有差距。但是只要再做一下微调应该就可以了,微调的话就是修改过的图片大小比最终大小还大的话,就进行0.8的压缩再比较,循环直到大小合适。这样就能得到合适大小的图片,而且也能比较保证质量。

4、jni调用libjpeg库压缩

jni静态调用 bitherlibjni.c 中的方法来实现压缩java_net_bither_util_nativeutil_compressbitmap

net_bither_util为包名,nativeutil为类名,compressbitmap为native方法名,我们只需要调用savebitmap()方法就可以,bmp 需要压缩的bitmap对象, quality压缩质量0-100, filename 压缩后要保存的文件地址, optimize 是否采用哈弗曼表数据计算 品质相差5-10倍。

jstring java_net_bither_util_nativeutil_compressbitmap(jnienv* env,
 jobject thiz, jobject bitmapcolor, int w, int h, int quality,
 jbytearray filenamestr, jboolean optimize) {

 androidbitmapinfo infocolor;
 byte* pixelscolor;
 int ret;
 byte * data;
 byte *tmpdata;
 char * filename = jstrintostring(env, filenamestr);
 if ((ret = androidbitmap_getinfo(env, bitmapcolor, &infocolor)) < 0) {
 loge("androidbitmap_getinfo() failed ! error=%d", ret);
 return (*env)->newstringutf(env, "0");;
 }
 if ((ret = androidbitmap_lockpixels(env, bitmapcolor, &pixelscolor)) < 0) {
 loge("androidbitmap_lockpixels() failed ! error=%d", ret);
 }

 byte r, g, b;
 data = null;
 data = malloc(w * h * 3);
 tmpdata = data;
 int j = 0, i = 0;
 int color;
 for (i = 0; i < h; i++) {
 for (j = 0; j < w; j++) {
 color = *((int *) pixelscolor);
 r = ((color & 0x00ff0000) >> 16);
 g = ((color & 0x0000ff00) >> 8);
 b = color & 0x000000ff;
 *data = b;
 *(data + 1) = g;
 *(data + 2) = r;
 data = data + 3;
 pixelscolor += 4;

 }

 }
 androidbitmap_unlockpixels(env, bitmapcolor);
 int resultcode= generatejpeg(tmpdata, w, h, quality, filename, optimize);
 free(tmpdata);
 if(resultcode==0){
 jstring result=(*env)->newstringutf(env, error);
 error=null;
 return result;
 }
 return (*env)->newstringutf(env, "1"); //success
}

5、质量压缩+采样率压缩+jni调用libjpeg库压缩结合使用

首先通过尺寸压缩,压缩到手机常用的一个分辨率(1280*960 微信好像是压缩到这个分辨率),然后我们要把图片压缩到一定大小以内(比如说200k),然后通过循环进行质量压缩来计算options需要设置为多少,最后调用jni压缩。

计算缩放比

/**
 * 计算缩放比
 * @param bitwidth 当前图片宽度
 * @param bitheight 当前图片高度
 * @return int 缩放比
 */
 public static int getratiosize(int bitwidth, int bitheight) {
 // 图片最大分辨率
 int imageheight = 1280;
 int imagewidth = 960;
 // 缩放比
 int ratio = 1;
 // 缩放比,由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
 if (bitwidth > bitheight && bitwidth > imagewidth) {
 // 如果图片宽度比高度大,以宽度为基准
 ratio = bitwidth / imagewidth;
 } else if (bitwidth < bitheight && bitheight > imageheight) {
 // 如果图片高度比宽度大,以高度为基准
 ratio = bitheight / imageheight;
 }
 // 最小比率为1
 if (ratio <= 0)
 ratio = 1;
 return ratio;
 }

质量压缩+jni压缩

/**
 * @description: 通过jni图片压缩把bitmap保存到指定目录
 * @param curfilepath
 * 当前图片文件地址
 * @param targetfilepath
 * 要保存的图片文件地址
 */
 public static void compressbitmap(string curfilepath, string targetfilepath) {
 // 最大图片大小 500kb
 int maxsize = 500;
 //根据地址获取bitmap
 bitmap result = getbitmapfromfile(curfilepath);
 bytearrayoutputstream baos = new bytearrayoutputstream();
 // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
 int quality = 100;
 result.compress(bitmap.compressformat.jpeg, quality, baos);
 // 循环判断如果压缩后图片是否大于500kb,大于继续压缩
 while (baos.tobytearray().length / 1024 > maxsize) {
 // 重置baos即清空baos
 baos.reset();
 // 每次都减少10
 quality -= 10;
 // 这里压缩quality,把压缩后的数据存放到baos中
 result.compress(bitmap.compressformat.jpeg, quality, baos);
 }
 // jni保存图片到sd卡 这个关键
 nativeutil.savebitmap(result, quality, targetfilepath, true);
 // 释放bitmap
 if (!result.isrecycled()) {
 result.recycle();
 }
 }

jni图片压缩工具类

package net.bither.util;
import android.graphics.bitmap;
import android.graphics.bitmap.config;
import android.graphics.bitmapfactory;
import android.graphics.canvas;
import android.graphics.matrix;
import android.graphics.rect;
import android.media.exifinterface;
import java.io.bytearrayoutputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
/**
* jni图片压缩工具类
*
* @description todo
* @package net.bither.util
* @class nativeutil
*/
public class nativeutil {

 private static int default_quality = 95;

 /**
 * @description: jni基本压缩
 * @param bit
 * bitmap对象
 * @param filename
 * 指定保存目录名
 * @param optimize
 * 是否采用哈弗曼表数据计算 品质相差5-10倍
 */
 public static void compressbitmap(bitmap bit, string filename, boolean optimize) {
 savebitmap(bit, default_quality, filename, optimize);
 }

 /**
 * @description: 通过jni图片压缩把bitmap保存到指定目录
 * @param image
 * bitmap对象
 * @param filepath
 * 要保存的指定目录
 */
 public static void compressbitmap(bitmap image, string filepath) {
 // 最大图片大小 150kb
 int maxsize = 150;
 // 获取尺寸压缩倍数
 int ratio = nativeutil.getratiosize(image.getwidth(),image.getheight());
 // 压缩bitmap到对应尺寸
 bitmap result = bitmap.createbitmap(image.getwidth() / ratio,image.getheight() / ratio, config.argb_8888);
 canvas canvas = new canvas(result);
 rect rect = new rect(0, 0, image.getwidth() / ratio, image.getheight() / ratio);
 canvas.drawbitmap(image,null,rect,null);
 bytearrayoutputstream baos = new bytearrayoutputstream();
 // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
 int options = 100;
 result.compress(bitmap.compressformat.jpeg, options, baos);
 // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
 while (baos.tobytearray().length / 1024 > maxsize) {
 // 重置baos即清空baos
 baos.reset();
 // 每次都减少10
 options -= 10;
 // 这里压缩options%,把压缩后的数据存放到baos中
 result.compress(bitmap.compressformat.jpeg, options, baos);
 }
 // jni保存图片到sd卡 这个关键
 nativeutil.savebitmap(result, options, filepath, true);
 // 释放bitmap
 if (!result.isrecycled()) {
 result.recycle();
 }
 }

 /**
 * @description: 通过jni图片压缩把bitmap保存到指定目录
 * @param curfilepath
 * 当前图片文件地址
 * @param targetfilepath
 * 要保存的图片文件地址
 */
 public static void compressbitmap(string curfilepath, string targetfilepath) {
 // 最大图片大小 500kb
 int maxsize = 500;
 //根据地址获取bitmap
 bitmap result = getbitmapfromfile(curfilepath);
 bytearrayoutputstream baos = new bytearrayoutputstream();
 // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
 int quality = 100;
 result.compress(bitmap.compressformat.jpeg, quality, baos);
 // 循环判断如果压缩后图片是否大于500kb,大于继续压缩
 while (baos.tobytearray().length / 1024 > maxsize) {
 // 重置baos即清空baos
 baos.reset();
 // 每次都减少10
 quality -= 10;
 // 这里压缩quality,把压缩后的数据存放到baos中
 result.compress(bitmap.compressformat.jpeg, quality, baos);
 }
 // jni保存图片到sd卡 这个关键
 nativeutil.savebitmap(result, quality, targetfilepath, true);
 // 释放bitmap
 if (!result.isrecycled()) {
 result.recycle();
 }

 }

 /**
 * 计算缩放比
 * @param bitwidth 当前图片宽度
 * @param bitheight 当前图片高度
 * @return int 缩放比
 */
 public static int getratiosize(int bitwidth, int bitheight) {
 // 图片最大分辨率
 int imageheight = 1280;
 int imagewidth = 960;
 // 缩放比
 int ratio = 1;
 // 缩放比,由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
 if (bitwidth > bitheight && bitwidth > imagewidth) {
 // 如果图片宽度比高度大,以宽度为基准
 ratio = bitwidth / imagewidth;
 } else if (bitwidth < bitheight && bitheight > imageheight) {
 // 如果图片高度比宽度大,以高度为基准
 ratio = bitheight / imageheight;
 }
 // 最小比率为1
 if (ratio <= 0)
 ratio = 1;
 return ratio;
 }

 /**
 * 通过文件路径读获取bitmap防止oom以及解决图片旋转问题
 * @param filepath
 * @return
 */
 public static bitmap getbitmapfromfile(string filepath){
 bitmapfactory.options newopts = new bitmapfactory.options();
 newopts.injustdecodebounds = true;//只读边,不读内容 
 bitmapfactory.decodefile(filepath, newopts);
 int w = newopts.outwidth;
 int h = newopts.outheight;
 // 获取尺寸压缩倍数
 newopts.insamplesize = nativeutil.getratiosize(w,h);
 newopts.injustdecodebounds = false;//读取所有内容
 newopts.indither = false;
 newopts.inpurgeable=true;
 newopts.ininputshareable=true;
 newopts.intempstorage = new byte[32 * 1024];
 bitmap bitmap = null;
 file file = new file(filepath);
 fileinputstream fs = null;
 try {
 fs = new fileinputstream(file);
 } catch (filenotfoundexception e) {
 e.printstacktrace();
 }
 try {
 if(fs!=null){
 bitmap = bitmapfactory.decodefiledescriptor(fs.getfd(),null,newopts);
 //旋转图片
 int photodegree = readpicturedegree(filepath);
 if(photodegree != 0){
  matrix matrix = new matrix();
  matrix.postrotate(photodegree);
  // 创建新的图片
  bitmap = bitmap.createbitmap(bitmap, 0, 0,
  bitmap.getwidth(), bitmap.getheight(), matrix, true);
 }
 }
 } catch (ioexception e) {
 e.printstacktrace();
 } finally{
 if(fs!=null) {
 try {
  fs.close();
 } catch (ioexception e) {
  e.printstacktrace();
 }
 }
 }
 return bitmap;
 }

 /**
 *
 * 读取图片属性:旋转的角度
 * @param path 图片绝对路径
 * @return degree旋转的角度
 */

 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;
 }

 /**
 * 调用native方法
 * @description:函数描述
 * @param bit
 * @param quality
 * @param filename
 * @param optimize
 */
 private static void savebitmap(bitmap bit, int quality, string filename, boolean optimize) {
 compressbitmap(bit, bit.getwidth(), bit.getheight(), quality, filename.getbytes(), optimize);
 }

 /**
 * 调用底层 bitherlibjni.c中的方法
 * @description:函数描述
 * @param bit
 * @param w
 * @param h
 * @param quality
 * @param filenamebytes
 * @param optimize
 * @return
 */
 private static native string compressbitmap(bitmap bit, int w, int h, int quality, byte[] filenamebytes,
   boolean optimize);
 /**
 * 加载lib下两个so文件
 */
 static {
 system.loadlibrary("jpegbither");
 system.loadlibrary("bitherjni");
 }
}

图片压缩处理中可能遇到的问题:

请求系统相册有三个action

注意:图库(缩略图) 和 图片(原图)

action_open_document 仅限4.4或以上使用 默认打开原图

从图片获取到的uri 格式为:content://com.android.providers.media.documents/document/image%666>>>

action_get_content 4.4以下默认打开缩略图 。 以上打开文件管理器 供选择,选择图库打开为缩略图页面,选择图片打开为原图浏览。

从图库获取到的uri格式为:content://media/external/images/media/666666

action_pick 都可用,打开默认是缩略图界面,还需要进一步点开查看。

参考代码:

public void pickfromgallery() {
 if (build.version.sdk_int < build.version_codes.kitkat) {
 startactivityforresult(new intent(intent.action_get_content).settype("image/*"),
 request_pick_image);
 } else {
 intent intent = new intent(intent.action_open_document);
 intent.addcategory(intent.category_openable);
 intent.settype("image/*");
 startactivityforresult(intent, request_kitkat_pick_image);
 }
}

根据uri获取对应的文件路径

在我们从图库中选择图片后回调给我们的data.getdata()可能是uri,我们平时对文件的操作基本上都是基于路径然后进行各种操作与转换,如今我们需要将uri对应的文件路径找出来,具体参考代码如下:

public static string getpathbyuri(context context, uri data){
 if (build.version.sdk_int < build.version_codes.kitkat) {
 return getpathbyuri4beforekitkat(context, data);
 }else {
 return getpathbyuri4afterkitkat(context, data);
 }
 }
 //4.4以前通过uri获取路径:data是uri,filename是一个string的字符串,用来保存路径
 public static string getpathbyuri4beforekitkat(context context, uri data) {
 string filename=null;
 if (data.getscheme().tostring().compareto("content") == 0) {
 cursor cursor = context.getcontentresolver().query(data, new string[] { "_data" }, null, null, null);
 if (cursor.movetofirst()) {
 filename = cursor.getstring(0);
 }
 } else if (data.getscheme().tostring().compareto("file") == 0) {// file:///开头的uri
 filename = data.tostring().replace("file://", "");// 替换file://
 if (!filename.startswith("/mnt")) {// 加上"/mnt"头
 filename += "/mnt";
 }
 }
 return filename;
 }
 //4.4以后根据uri获取路径:
 @suppresslint("newapi")
 public static string getpathbyuri4afterkitkat(final context context, final uri uri) {
 final boolean iskitkat = build.version.sdk_int >= build.version_codes.kitkat;
 // documentprovider
 if (iskitkat && documentscontract.isdocumenturi(context, uri)) {
 if (isexternalstoragedocument(uri)) {// externalstorageprovider
 final string docid = documentscontract.getdocumentid(uri);
 final string[] split = docid.split(":");
 final string type = split[0];
 if ("primary".equalsignorecase(type)) {
  return environment.getexternalstoragedirectory() + "/" + split[1];
 }
 } else if (isdownloadsdocument(uri)) {// downloadsprovider
 final string id = documentscontract.getdocumentid(uri);
 final uri contenturi = contenturis.withappendedid(uri.parse("content://downloads/public_downloads"),
  long.valueof(id));
 return getdatacolumn(context, contenturi, null, null);
 } else if (ismediadocument(uri)) {// mediaprovider
 final string docid = documentscontract.getdocumentid(uri);
 final string[] split = docid.split(":");
 final string type = split[0];
 uri contenturi = null;
 if ("image".equals(type)) {
  contenturi = mediastore.images.media.external_content_uri;
 } else if ("video".equals(type)) {
  contenturi = mediastore.video.media.external_content_uri;
 } else if ("audio".equals(type)) {
  contenturi = mediastore.audio.media.external_content_uri;
 }
 final string selection = "_id=?";
 final string[] selectionargs = new string[] { split[1] };
 return getdatacolumn(context, contenturi, selection, selectionargs);
 }
 } else if ("content".equalsignorecase(uri.getscheme())) {// mediastore
 // (and
 // general)
 return getdatacolumn(context, uri, null, null);
 } else if ("file".equalsignorecase(uri.getscheme())) {// file
 return uri.getpath();
 }
 return null;
 }

 /**
 * get the value of the data column for this uri. this is useful for
 * mediastore uris, and other file-based contentproviders.
 *
 * @param context
 * the context.
 * @param uri
 * the uri to query.
 * @param selection
 * (optional) filter used in the query.
 * @param selectionargs
 * (optional) selection arguments used in the query.
 * @return the value of the _data column, which is typically a file path.
 */
 public static string getdatacolumn(context context, uri uri, string selection, string[] selectionargs) {
 cursor cursor = null;
 final string column = "_data";
 final string[] projection = { column };
 try {
 cursor = context.getcontentresolver().query(uri, projection, selection, selectionargs, null);
 if (cursor != null && cursor.movetofirst()) {
 final int column_index = cursor.getcolumnindexorthrow(column);
 return cursor.getstring(column_index);
 }
 } finally {
 if (cursor != null)
 cursor.close();
 }
 return null;
 }

 /**
 * @param uri
 * the uri to check.
 * @return whether the uri authority is externalstorageprovider.
 */
 public static boolean isexternalstoragedocument(uri uri) {
 return "com.android.externalstorage.documents".equals(uri.getauthority());
 }

 /**
 * @param uri
 * the uri to check.
 * @return whether the uri authority is downloadsprovider.
 */
 public static boolean isdownloadsdocument(uri uri) {
 return "com.android.providers.downloads.documents".equals(uri.getauthority());
 }

 /**
 * @param uri
 * the uri to check.
 * @return whether the uri authority is mediaprovider.
 */
 public static boolean ismediadocument(uri uri) {
 return "com.android.providers.media.documents".equals(uri.getauthority());
 }

源码奉上,自行参考:源码下载

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网