Android性能优化之图片大小,尺寸压缩的方法

发布时间:2022-04-18 13:37:57 作者:iii
来源:亿速云 阅读:319

这篇文章主要介绍“Android性能优化之图片大小,尺寸压缩的方法”,在日常操作中,相信很多人在Android性能优化之图片大小,尺寸压缩的方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Android性能优化之图片大小,尺寸压缩的方法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

前言

在Android中我们经常会遇到图片压缩的场景,比如给服务端上传图片,包括个人信息的用户头像,有时候人脸识别也需要捕获图片等等。这种情况下,我们都需要对图片做一定的处理,比如大小,尺寸等的压缩。

常见的图片压缩方法

质量压缩

首先我们要介绍一个api--Bitmap.compress()

@WorkerThread
public boolean compress(CompressFormat format, int quality, OutputStream stream) {
    checkRecycled("Can't compress a recycled bitmap");
    // do explicit check before calling the native method
    if (stream == null) {
        throw new NullPointerException();
    }
    if (quality < 0 || quality > 100) {
        throw new IllegalArgumentException("quality must be 0..100");
    }
    StrictMode.noteSlowCall("Compression of a bitmap is slow");
    Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "Bitmap.compress");
    boolean result = nativeCompress(mNativePtr, format.nativeInt,
            quality, stream, new byte[WORKING_COMPRESS_STORAGE]);
    Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
    return result;
}

compress()是系统的API,也是质量和尺寸压缩常用的方法。

public boolean compress(Bitmap.CompressFormat format, int quality, OutputStream stream);这个方法有三个参数:

返回值:如果成功地把压缩数据写入输出流,则返回true。

伪代码

val baos= ByteArrayoutputstream ()
    try {
        var quality = 50
        do {
            quality -= 10
            baos.reset()
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos)
        } while (baos.toByteArray().size / 1024 > 100)
        fos.write(baos.toByteArray(o))
    }catch (ex : Throwable) {
        ex.printStackTrace ()} finally {
        fos.apply i this: FileOutputStream
        flush ()
        close ()
    }

尺寸压缩

先来看看一个属性Options

两次decode,传入不同的options配置:

Android性能优化之图片大小,尺寸压缩的方法

部分伪代码

    val reqWidth = 500
    val reqHeight = 300
    val bitmap = decodeSampledBitmapFromFile(imageFile, reqWidth, reqHeight)
    val fos = Fileoutputstream(
            File(applicationContext.filesDir,
                    child: "$ {system.currentTimeMillis() }_scale.jpg")
    )
    try {
        val quality = 50
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos)
        catch(ex: Throwable) {
            ex.printstackTrace() finally {
                fos.apply {
                    flush()
                    close()

                }
            }
        }
    }
}

private fun decodeSampledBitmapFromFile(imageFile: File,reqWidth: Int,reqHeight: Int): Bitmap
{
    return BitmapFactory.Options().run {
        inJustDecodeBounds = true
        //先获取原始图片的宽高,不会将Bitmap加载到内存中,返回null
        BitmapFactory.decodeFile(imageFile.absolutePath, opts: this)
        inSamplesize = calculateInSampleSize(options: this, reqWidth,reqHeight)
        inJustDecodeBounds - false
        BitmapFactory.decodeFile(imageFile.absolutePath, opts : this)
    }
}

private fun calculateInSampleSize(context: BitmapFactory, reqWidth: Int, reqHeight: Int): Int {
    //解构语法,获取原始图片的宽高
    val (height: Int, width: Int) = options.run { outHeight to outwidth }
    //计算最大的inSampleSize值,该值为2的幂次方,并同时保持这两个值高度和宽度大于请求的高度和宽度。
    //原始图片的宽高要大于要求的宽高
    var inSampleSize = 1
    if (height > reqHeight || width > reqWidth) {
        val halfHeight: Int = height / 2
        val halfwidth: Int = width / 2
        while (halfHeight / inSampleSize >= reqHeight && halfwidth / inSampleSize >= reqWidth) {
            inSampleSize *= 2
        }
    }
    return inSampleSize
}

inSampleSize都是2的倍数 .

BitmapFactory 给我们提供了一个解析图片大小的参数类 BitmapFactory.Options ,把这个类的对象的 inJustDecodeBounds 参数设置为 true,这样解析出来的 Bitmap 虽然是个 null,但是 options 中可以得到图片的宽和高以及图片的类型。得到了图片实际的宽和高之后我们就可以进行压缩设置了,主要是计算图片的采样率。

libjpeg

图片压缩流程

Android性能优化之图片大小,尺寸压缩的方法

其实最重要的是把ARGB转换为RBG,也就是把每个像素4个字节,转换为每个像素3个字节。

导入对应的so库文件即可编写C的代码 jpeg.so 和 jpeg-turbo.so

编写这部分的代码需要NDK的环境和C语言的基础

伪代码

int generateCompressJPEG(BYTE *data, int w, int h, int quality, const char *outfileName, jboolean optimize) {
    //结构体相当于java的类
    struct jpeg_compress_struct jcs;
    //当读完整个文件的时候回回调
    struct my_error_mgr jem;
    jcs.err = jpeg_std_error(&jem.pub);
    jem.pub.error_exit = my_error_exit;
    //setjmp是一个系统级函数,是一个回调
    if (setjmp(jem.setjmp_buffer)) {
        return 0;
    }
    //初始化jsc结构体
    jpeg_create_compress(&jcs);
    //打开输出文件  wb可写  rb可读
    FILE *f = fopen(outfileName, "wb");
    if (f == NULL) {
        return 0;
    }
    //设置结构体的文件路径,以及宽高
    jpeg_stdio_dest(&jcs, f);
    jcs.image_width = w;
    jcs.image_height = h;
    //TRUE=arithmetic coding, FALSE=Huffman
    jcs.arith_code = false;
    int nComponent = 3;
    // 颜色的组成rgb,三个 of color components in input image
    jcs.input_components = nComponent;
    // 设置颜色空间为rgb
    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_pointer[1];
    int row_stride;
    row_stride = jcs.image_width * nComponent;
    while (jcs.next_scanline < jcs.image_height) {
        //得到一行的首地址
        row_pointer[0] = &data[jcs.next_scanline * row_stride];
        jpeg_write_scanlines(&jcs, row_pointer, 1);
    }
    // 压缩结束
    jpeg_finish_compress(&jcs);
    // 销毁回收内存
    jpeg_destroy_compress(&jcs);
    //关闭文件
    fclose(f);
    return 1;
}
for (int i = 0; i < bitmapInfo.height; ++i) {
    for (int j= 0; j < bitmapInfo.width; ++j){
        if (bitmapInfo.format == ANDROID_BITMAP_FORMAT_RGBA_8888){
            //0x2312faff ->588446463
            color = *(int *) (pixelsColor);
            // 从color值中读取RGBA的值/ /ABGR
            b = (color >> 16)& 0xFE;
            g = (color >> 8)& OxFF;
            r = (color >> 0) & OxFF;
            *data = r;
            * (data + 1) =g;
            *(data + 2) = b;
            data += 3;
            //移动步长4个字节
            pixelsColor +- 4 ;
        }else {
            return -2;
        }
        
    // 是否采用哈夫曼
     jcs.optimize_coding = optimize;

至此,三种图片压缩的方法已经介绍完毕了。

总结

经过图片压缩实践,质量压缩和libjpeg最后的图片的大小一样,效果也和原图差不多。

其实,经过我翻查原码发现,新版本的Bitmap.compress() 会调用

boolean result = nativeCompress(mNativePtr, format.nativeInt,
        quality, stream, new byte[WORKING_COMPRESS_STORAGE]);

private static native boolean nativeCompress(long nativeBitmap, int format,
                                        int quality, OutputStream stream,
                                        byte[] tempStorage);

其实最后也会调用到nativeCompress的压缩,也会采用哈夫曼算法,提高压缩效率。

既然这样,那么这里为什么还要介绍libjpeg的方法呢?

到此,关于“Android性能优化之图片大小,尺寸压缩的方法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. HTML改变图片大小的方法
  2. html如何定义图像及其图片大小尺寸

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android

上一篇:mongodb数据块怎么迁移

下一篇:C语言栈、堆和静态存储区怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》