糖尿病康复,内容丰富有趣,生活中的好帮手!
糖尿病康复 > **Android 图片处理系列:图片压缩处理

**Android 图片处理系列:图片压缩处理

时间:2018-09-26 10:06:59

相关推荐

**Android 图片处理系列:图片压缩处理

Android 图片处理系列:图片压缩处理

由于公司主打的旅游产品,对图片处理的比较多,不仅要处理显示大批量的功能,还要有拍照上传和本地图片上传的功能,这就要求在上传之前需要对图片进行压缩处理,同时需要将照片的附加属性如:创建时间、经纬度等同时上传,所以就需要在把压缩前的图片属性写入压缩后的图片。

一般针对Android压缩图片 :

Android中有两种压缩图片的方法:

第一种是针对图片的长宽进行压缩,在将图片加载到内存过程中将图片的长宽进行压缩,获取长宽压缩版的的图片

第二种是针对图片的像素进行压缩,图片加载到内存后,针对图片质量进行压缩,会导致图片质量下降。

如果不了解上面两种该怎么去进行的可以看这篇文章,我就不再具体写了: /p/0f56f35068e2

如果不想用Android自带的压缩图片方式可以使用libjpeg库压缩,这就涉及到NDK方面,有兴趣可以看看这篇文章:/hqiong208/article/details/53667661

先进行长宽压缩:

/** * 根据路径获得突破并压缩返回bitmap用于显示 * @param filePath 图片的路径 需要压缩图片的路径* @param reqWidth 要求的图片的像素 根据主流一般720*1280* @param reqHeight 要求的图片的像素 * @return */ public static Bitmap getBitmap(String filePath,int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); options.inSampleSize = inSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filePath, options); } public static int inSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (width<=height){//竖屏拍照if (height > reqHeight || width > reqWidth) {final int heightRatio = Math.round((float) height/ (float) reqHeight);final int widthRatio = Math.round((float) width / (float) reqWidth);inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}}else {//横屏if (height > reqWidth || width > reqHeight) {final int heightRatio = Math.round((float) height/ (float) reqWidth);final int widthRatio = Math.round((float) width / (float) reqHeight);inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}}return inSampleSize; }

再进行质量压缩,quality(0~100) 自己指定,一般60到70就好,并不会太失真

/** * @param file 压缩后的图片文件* @param bm * @return */ public static void saveBitmap(Bitmap bm, File file) {//质量try {FileOutputStream out = new FileOutputStream(file);press(pressFormat.JPEG, 70, out);out.flush();out.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

写入图片属性:采用的是ExifInterface,代码有点多就不贴了,其实也很简单主要就是getAttribute,setAttribute,saveAttributes,不了解可以查查,非常简单。

当然具体情况具体分析,如果是拍照上传,一般都是1M以上,长宽质量都要压缩,但是本地图片上传,有的只有100多k或更小,那么质量压缩是否可以不要压缩或者 quality设置更高一点,这需要根据实际来判断。

实际达到的效果,拍照后2、3M的照片压缩后只有200k左右,基本不失真。

最后推荐一种压缩格式WebP,亲身体检在相同方式下WebP格式压缩会比Jpng更小接近一倍的体积,而且效果差不多。可以看看这篇文章:/a/anzhuokaifa/androidkaifa//0527/4302.html

如果觉得《**Android 图片处理系列:图片压缩处理》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。