ZUI易入门Android之libjpeg实现图片压缩

tech2022-09-12  102

Android中图片是以bitmap形式存在的,那么bitmap所占内存,直接影响到了应用所占内存大小,首先要知道bitmap所占内存大小计算方式:

图片长度 x 图片宽度 x 一个像素点占用的字节数

以下是图片的压缩格式:

其中,A代表透明度;R代表红色;G代表绿色;B代表蓝色。

ALPHA_8  表示8位Alpha位图,即A=8,一个像素点占用1个字节,它没有颜色,只有透明度  ARGB_4444  表示16位ARGB位图,即A=4,R=4,G=4,B=4,一个像素点占4+4+4+4=16位,2个字节  ARGB_8888  表示32位ARGB位图,即A=8,R=8,G=8,B=8,一个像素点占8+8+8+8=32位,4个字节  RGB_565  表示16位RGB位图,即R=5,G=6,B=5,它没有透明度,一个像素点占5+6+5=16位,2个字节

我是用的小米手机2s来测试的,从sd卡取出一个照片,如下所示:

bit = BitmapFactory.decodeFile(Environment                 .getExternalStorageDirectory().getAbsolutePath()                 + "/DCIM/Camera/test.jpg");           Log.i("wechat", "压缩前图片的大小" + (bit.getByteCount() / 1024 / 1024)                 + "M宽度为" + bit.getWidth() + "高度为" + bit.getHeight());

出来的log是:

将取得的bitmap进行压缩,下面开始说,bitmap的几种压缩方式。

1.质量压缩

            ByteArrayOutputStream baos = new ByteArrayOutputStream();             int quality = Integer.valueOf(editText.getText().toString());             bit.compress(CompressFormat.JPEG, quality, baos);             byte[] bytes = baos.toByteArray();             bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);             Log.i("wechat", "压缩后图片的大小" + (bm.getByteCount() / 1024 / 1024)                     + "M宽度为" + bm.getWidth() + "高度为" + bm.getHeight()                     + "bytes.length=  " + (bytes.length / 1024) + "KB"                     + "quality=" + quality);

其中quality是从edittext获取的数字,可以从0–100改变,这里出来的log是: 

可以看到,图片的大小是没有变的,因为质量压缩不会减少图片的像素,它是在保持像素的前提下改变图片的位深及透明度等,来达到压缩图片的目的,这也是为什么该方法叫质量压缩方法。那么,图片的长,宽,像素都不变,那么bitmap所占内存大小是不会变的。

但是我们看到bytes.length是随着quality变小而变小的。这样适合去传递二进制的图片数据,比如微信分享图片,要传入二进制数据过去,限制32kb之内。

这里要说,如果是bit.compress(CompressFormat.PNG, quality, baos);这样的png格式,quality就没有作用了,bytes.length不会变化,因为png图片是无损的,不能进行压缩。

CompressFormat还有一个属性是,CompressFormat.WEBP格式,该格式是google自己推出来一个图片格式,更多信息,文末会贴出地址。

2.采样率压缩

BitmapFactory.Options options = new BitmapFactory.Options();             options.inSampleSize = 2;               bm = BitmapFactory.decodeFile(Environment                     .getExternalStorageDirectory().getAbsolutePath()                     + "/DCIM/Camera/test.jpg", options);             Log.i("wechat", "压缩后图片的大小" + (bm.getByteCount() / 1024 / 1024)                     + "M宽度为" + bm.getWidth() + "高度为" + bm.getHeight());

设置inSampleSize的值(int类型)后,假如设为2,则宽和高都为原来的1/2,宽高都减少了,自然内存也降低了。

我上面的代码没用过options.inJustDecodeBounds = true; 因为我是固定来取样的数据,为什么这个压缩方法叫采样率压缩,是因为配合inJustDecodeBounds,先获取图片的宽、高【这个过程就是取样】,然后通过获取的宽高,动态的设置inSampleSize的值。

当inJustDecodeBounds设置为true的时候,BitmapFactory通过decodeResource或者decodeFile解码图片时,将会返回空(null)的Bitmap对象,这样可以避免Bitmap的内存分配,但是它可以返回Bitmap的宽度、高度以及MimeType。

3.缩放法压缩(martix)

Matrix matrix = new Matrix();             matrix.setScale(0.5f, 0.5f);             bm = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),                     bit.getHeight(), matrix, true);             Log.i("wechat", "压缩后图片的大小" + (bm.getByteCount() / 1024 / 1024)                     + "M宽度为" + bm.getWidth() + "高度为" + bm.getHeight());

可以看出来,bitmap的长度和宽度分别缩小了一半,图片大小缩小了四分之一。  关于martix更多信息,文末会有一个参考文章

4.RGB_565法

BitmapFactory.Options options2 = new BitmapFactory.Options();             options2.inPreferredConfig = Bitmap.Config.RGB_565;               bm = BitmapFactory.decodeFile(Environment                     .getExternalStorageDirectory().getAbsolutePath()                     + "/DCIM/Camera/test.jpg", options2);             Log.i("wechat", "压缩后图片的大小" + (bm.getByteCount() / 1024 / 1024)                     + "M宽度为" + bm.getWidth() + "高度为" + bm.getHeight());

 

 

出来的log是

我们看到图片大小直接缩小了一半,长度和宽度也没有变,相比argb_8888减少了一半的内存。

注意:由于ARGB_4444的画质惨不忍睹,一般假如对图片没有透明度要求的话,可以改成RGB_565,相比ARGB_8888将节省一半的内存开销。

5.createScaledBitmap

bm = Bitmap.createScaledBitmap(bit, 150, 150, true);             Log.i("wechat", "压缩后图片的大小" + (bm.getByteCount() / 1024) + "KB宽度为"                     + bm.getWidth() + "高度为" + bm.getHeight());

总结

以上就是5种图片压缩的方法,这里需要强调,他们的压缩仅仅只是对android中的bitmap来说的。如果将这些压缩后的bitmap另存为sd中,他们的内存大小并不一样。

android手机中,图片的所占的内存大小和很多因素相关,计算起来也很麻烦。为了计算出一个图片的内存大小,可以将图片当做一个文件来间接计算,用如下的方法:

 File file = new File(Environment.getExternalStorageDirectory()          .getAbsolutePath() + "/DCIM/Camera/test.jpg");          Log.i("wechat", "file.length()=" + file.length() / 1024);

或者

FileInputStream fis = null;         try {             fis = new FileInputStream(file);         } catch (FileNotFoundException e) {             e.printStackTrace();         }         try {             Log.i("wechat", "fis.available()=" + fis.available() / 1024);         } catch (IOException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }

 

上面两个方法计算的结果是一样的。

看完了这篇内容,其实说白了,Bitmap压缩都是围绕这个来做文章:Bitmap所占用的内存 = 图片长度 x 图片宽度 x 一个像素点占用的字节数。3个参数,任意减少一个的值,就达到了压缩的效果。

参考文章:  Android Bitmap 优化(1) - 图片压缩http://anany.me/2015/10/15/bitmap1/

多图比较谷歌WebP和JPEG图像格式http://www.win7china.com/html/8668.html

Android-使用Matrix对Bitmap进行处理http://blog.csdn.net/nupt123456789/article/details/24600055

 

 

一、Android中使用的图片压缩库 Android和IOS 中图片处理使用了一个叫做skia的开源图形处理引擎。他位于android源码的/external/skia 目录。我们平时在java层使用一个图片处理的函数实际上底层就是调用了这个开源引擎中的相关的函数。二、Android 中常用的压缩方式 Android中常用压缩方法分为2种:一种是降采样率压缩,另外一种是质量压缩。 代码: 1.降采样率压缩的一般写法:

  public static Bitmap obtainImageFromPath(String path, int width, int height) {         BitmapFactory.Options o = new BitmapFactory.Options();         o.inJustDecodeBounds = true;         BitmapFactory.decodeFile(path, o);         o.inSampleSize = calculateSampleSize(o, width, height);         o.inJustDecodeBounds = false;         return BitmapFactory.decodeFile(path, o);     }

    private static int calculateSampleSize(BitmapFactory.Options o, int reqWidth, int reqHeight) {         int sampleSize = 1;         if (o.outWidth > reqWidth || o.outHeight > reqHeight) {             final int halfWidth = o.outWidth / 2;             final int halfHeight = o.outHeight / 2;             while ((halfHeight / sampleSize) >= reqHeight                     && (halfWidth / sampleSize) >= reqWidth) {                 sampleSize *= 2;             }         }         return sampleSize;     }

2.质量压缩的一般写法:

bitmap.compress(Bitmap.CompressFormat.JPEG, 20, new FileOutputStream("sdcard/result.jpg"));

三、libjpeg 我们使用质量压缩的话它的底层就是用skia引擎进行处理,加入我们调用bitmap.compress(Bitmap.CompressFormat.JPEG,…..) 他实际会 使用一个libjpeg.so 的动态库进行编码压缩。 android在进行jpeg压缩编码的时候,考虑到了效率问题使用了定长编码方式进行编码(因为当时的手机性能都比较低),而IOS使用了变长编码的算法——哈夫曼算法。而且IOS对skia引擎也做了优化。所有我们看到同样的图片在ios上压缩会好一点。

四、优化思路 上文我们知道之所以在android机进行质量压缩没有IOS上压缩好的原因,那么我们也就应该有了相应的优化思路。我们的思路如下: 1、下载开源的libjpeg,进行移植、编译得到libjpeg.so 2、使用jni编写一个函数用来图片压缩 3、在函数中添加一个开关选项,可以让我们选择是否使用哈夫曼算法。 4、打包,搞成sdk供我们以后使用。

五、实现 1、下载libjpeg 编译 使用git clone最新的android分支

git clone git://git.linaro.org/people/tomgall/libjpeg-turbo/libjpeg-turbo.git -b linaro-android

2、编译 记得配置好ndk,设置环境变量

1、把文件名变成 jni mv libjpeg-turbo jni 2、编译 ndk-build APP_ABI=armeabi-v7a,armeabi

3、使用AndroidStudio创建一个项目,记得勾选c++ support

4、加入编译好的 动态库,和头文件并且在在配置文件中引用

5、编写代码:

#include "compress.h" #include "lang.h"

#include <android/bitmap.h> #include <setjmp.h> #include <jpeglib.h>

#include <stdlib.h>

#define true 1 #define false 0

typedef u_int8_t BYTE;

struct my_error_mgr {     struct jpeg_error_mgr pub;     jmp_buf setjmp_buffer; };

typedef struct my_error_mgr *my_error_ptr;

METHODDEF(void)

my_error_exit(j_common_ptr               cinfo) {     my_error_ptr myerr = (my_error_ptr) cinfo->err;     (*cinfo->err->output_message)(cinfo);     LOGW("jpeg_message_table[%d]:%s",          myerr->pub.msg_code, myerr->pub.jpeg_message_table[myerr->pub.msg_code]);     longjmp(myerr                     ->setjmp_buffer, 1); }

int generateJPEG(BYTE *data, int w, int h, jint quality, const char *name, boolean optimize);

const char *jstringToString(JNIEnv *env, jstring jstr);

JNIEXPORT jint

JNICALL Java_com_blueberry_compress_ImageCompress_nativeCompressBitmap(JNIEnv *env, jclass type,                                                                jobject bitmap, jint quality,                                                                jstring dstFile_,                                                                jboolean optimize) {

    AndroidBitmapInfo androidBitmapInfo;     BYTE *pixelsColor;     int ret;     BYTE *data;     BYTE *tmpData;     const char *dstFileName = jstringToString(env, dstFile_);     //解码Android Bitmap信息     if ((ret = AndroidBitmap_getInfo(env, bitmap, &androidBitmapInfo)) < 0) {         LOGD("AndroidBitmap_getInfo() failed error=%d", ret);         return ret;     }     if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixelsColor)) < 0) {         LOGD("AndroidBitmap_lockPixels() failed error=%d", ret);         return ret;     }

    LOGD("bitmap: width=%d,height=%d,size=%d , format=%d ",          androidBitmapInfo.width, androidBitmapInfo.height,          androidBitmapInfo.height * androidBitmapInfo.width,          androidBitmapInfo.format);

    BYTE r, g, b;     int color;

    int w, h, format;     w = androidBitmapInfo.width;     h = androidBitmapInfo.height;     format = androidBitmapInfo.format;

    data = (BYTE *) malloc(androidBitmapInfo.width * androidBitmapInfo.height * 3);     tmpData = data;     // 将bitmap转换为rgb数据     for (int i = 0; i < h; ++i) {         for (int j = 0; j < w; ++j) {             //只处理 RGBA_8888             if (format == ANDROID_BITMAP_FORMAT_RGBA_8888) {                 color = (*(int *) (pixelsColor));                 // 这里取到的颜色对应的 A B G R  各占8位                 b = (color >> 16) & 0xFF;                 g = (color >> 8) & 0xFF;                 r = (color >> 0) & 0xFF;                 *data = r;                 *(data + 1) = g;                 *(data + 2) = b;

                data += 3;                 pixelsColor += 4;

            } else {                 return -2;             }         }     }     AndroidBitmap_unlockPixels(env, bitmap);     //进行压缩     ret = generateJPEG(tmpData, w, h, quality, dstFileName, optimize);     free((void *) dstFileName);     free((void *) tmpData);     return ret; }

int generateJPEG(BYTE *data, int w, int h, int quality, const char *name, boolean optimize) {     int nComponent = 3;     struct jpeg_compress_struct jcs;     //自定义的error     struct my_error_mgr jem;

    jcs.err = jpeg_std_error(&jem.pub);     jem.pub.error_exit = my_error_exit;

    if (setjmp(jem.setjmp_buffer)) {         return 0;     }     //为JPEG对象分配空间并初始化     jpeg_create_compress(&jcs);     //获取文件信息     FILE *f = fopen(name, "wb");     if (f == NULL) {         return 0;     }

    //指定压缩数据源     jpeg_stdio_dest(&jcs, f);     jcs.image_width = w;     jcs.image_height = h;

    jcs.arith_code = false;     jcs.input_components = nComponent;     jcs.in_color_space = JCS_RGB;

    jpeg_set_defaults(&jcs);     jcs.optimize_coding = optimize;

    //为压缩设定参数,包括图像大小,颜色空间     jpeg_set_quality(&jcs, quality, true);     //开始压缩     jpeg_start_compress(&jcs, true);     JSAMPROW row_point[1];     int row_stride;     row_stride = jcs.image_width * nComponent;     while (jcs.next_scanline < jcs.image_height) {         row_point[0] = &data[jcs.next_scanline * row_stride];         jpeg_write_scanlines(&jcs, row_point, 1);     }

    if (jcs.optimize_coding) {         LOGI("使用了哈夫曼算法完成压缩");     } else {         LOGI("未使用哈夫曼算法");     }     //压缩完毕     jpeg_finish_compress(&jcs);     //释放资源     jpeg_destroy_compress(&jcs);     fclose(f);     return 1; }

const char *jstringToString(JNIEnv *env, jstring jstr) {     char *ret;     const char *tempStr = (*env)->GetStringUTFChars(env, jstr, NULL);     jsize len = (*env)->GetStringUTFLength(env, jstr);     if (len > 0) {         ret = (char *) malloc(len + 1);         memcpy(ret, tempStr, len);         ret[len] = 0;     }     (*env)->ReleaseStringUTFChars(env, jstr, tempStr);     return ret; }

6、最后测试

我测试发现确实有些改善,使用同样的压缩等级,采用哈夫曼算法的话,会压缩的更小一些。

7、最后 代码地址:https://github.com/DapengLee/Compress

最新回复(0)