博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android 图片压缩
阅读量:4677 次
发布时间:2019-06-09

本文共 2175 字,大约阅读时间需要 7 分钟。

紧接上篇博文 , 在获取拍照拍下的图片并将其设为背景的时候出现了问题

系统给出了这样的警告:

Bitmap too large to be uploaded into a texture

意思很明显:就是现在的手机硬件越来越强悍了(-.-||).拍下来的图片太大,无法直接展示.

网上有说关闭硬件加速喝分片加载的办法.不过这都不是我想要的.这种问题自然是要压缩图片的

嘛!!

压缩代码:

/**     * 图片质量压缩     * **/    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            options -= 10;//每次都减少10            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中        }        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片        return bitmap;    }    /**     * 图片比例压缩     * */    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;        //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为        float hh = 800f;//这里设置高度为800f        float ww = 480f;//这里设置宽度为480f        //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可        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);//压缩好比例大小后再进行质量压缩 }

这是脚本之家的大神写的拿来膜拜.

大神链接:http://www.jb51.net/article/41117.htm

转载于:https://www.cnblogs.com/wobeinianqing/p/5493122.html

你可能感兴趣的文章
PAT-1134. Vertex Cover (25)
查看>>
git 命令图解
查看>>
分布式存储系统可靠性系列三:设计模式
查看>>
this关键字的由来及使用
查看>>
两个时间相差多少 .net中的timespan应用
查看>>
递归 换零钱问题——由打靶子问题引申
查看>>
Python-函数基础
查看>>
Extensible Messaging and Presence Protocol (XMPP) 简介
查看>>
Farm Irrigation
查看>>
windows平板的开发和选型
查看>>
无平方因子的数(数论初步) By ACReaper
查看>>
C语言截取字符串
查看>>
如何查自己的账单
查看>>
JAVA8学习笔记(二)----三个预定义接口
查看>>
JDBC连接各种数据库的字符串
查看>>
构建之法阅读笔记06
查看>>
CentOS minimal新装配置笔记
查看>>
压缩映象原理的一个应用
查看>>
Aurora — 一个在 MSOffice 内输入 LaTeX 公式的很好用插件
查看>>
关于sql优化的一个小总结
查看>>