一直使用的图片压缩的代码,做个笔记
2016-06-06 10:04
459 查看
废话不多说,直接贴代码,主要目的是做个笔记!很感谢提供这段代码的小伙伴,虽然忘记是从哪个网站上找到的了,真的很实用!
public void commit() { // TODO: 2016/5/23 0023 压缩图片 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(pics.get(i), options); int height = options.outHeight; int width = options.outWidth; int reqHeight = 0; int reqWidth = 480; reqHeight = (reqWidth * height) / width; // 在内存中创建bitmap对象,这个对象按照缩放大小创建的 options.inSampleSize = calculateInSampleSize( options, 480, reqHeight); options.inJustDecodeBounds = false; Bitmap bm = BitmapFactory.decodeFile( pics.get(i), options); bm = compressImage(Bitmap.createScaledBitmap( bm, 480, reqHeight, false)); bitmaps.add(bm); } // 压缩 private Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 image.compress(Bitmap.CompressFormat.JPEG, 80, baos); int options = 100; // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 while (baos.toByteArray().length / 1024 > 100) { options -= 10;// 每次都减少10 baos.reset();// 重置baos即清空baos // 这里压缩options%,把压缩后的数据存放到baos中 image.compress(Bitmap.CompressFormat.JPEG, options, baos); } // 把压缩后的数据baos存放到ByteArrayInputStream中 ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); // 把ByteArrayInputStream数据生成图片 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); return bitmap; } // 计算缩放大小 private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { if (width > height) { inSampleSize = Math.round((float) height / (float) reqHeight); } else { inSampleSize = Math.round((float) width / (float) reqWidth); } } return inSampleSize; }
相关文章推荐
- 如何在 Ubuntu Linux 中使用 RAR 文件
- 按右键另存图片只能存BMP
- photoshop去除图片上的水印
- upload上传单张图片
- 图片引发的溢出危机(图)
- C#实现把彩色图片灰度化代码分享
- C#将图片和字节流互相转换并显示到页面上
- C#使用DeflateStream解压缩数据文件的方法
- C#监控文件夹并自动给图片文件打水印的方法
- C# 利用ICSharpCode.SharpZipLib实现在线压缩和解压缩
- 纯CSS实现的当鼠标移上图片添加阴影效果代码
- 如何使用C#从word文档中提取图片
- C#实现打开画图的同时载入图片、最大化显示画图窗体的方法
- C#图片添加水印的实现代码
- 随鼠标移动的图片或文字特效代码
- CSS 图片横向排列实现代码
- C#实现将Email地址转成图片显示的方法
- C#实现图片加相框的方法
- 超级经典一套鼠标控制左右滚动图片带自动翻滚
- 用css实现图片垂直居中的使用技巧