第一部分: 不多说直接上代码,代码中在做仔细解释: private void imageZoom() {//图片允许最大空间 单位:KB double maxSize =400.00; //将bitmap放至数组中,意在bitmap的大小(与实际读取的原文件要大) ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); //将字节换成KB double mid = b.length/1024; //判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩 if (mid > maxSize) { //获取bitmap大小 是允许最大大小的多少倍 double i = mid / maxSize; //开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍 (1.保持刻度和高度和原bitmap比率一致,压缩后也达到了最大大小占用空间的大小) bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i), bitMap.getHeight() / Math.sqrt(i)); } } /*** * 图片的缩放方法 * * @param bgimage * :源图片资源 * @param newWidth * :缩放后宽度 * @param newHeight * :缩放后高度 * @return */ public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) { // 获取这个图片的宽和高 float width = bgimage.getWidth(); float height = bgimage.getHeight(); // 创建操作图片用的matrix对象 Matrix matrix = new Matrix(); // 计算宽高缩放率 float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // 缩放图片动作 matrix.postScale(scaleWidth, scaleHeight); Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true); return bitmap; } 压缩后的图片比预期要大10% 原因可能是bitmap图的宽高不一致,导致压缩误差!如有更好方法也请联系:690358889 希望能帮助各位
转自:http://www.eoeandroid.com/thread-174003-1-1.html 第二部分: Android的图片压缩类ThumbnailUtils从Android 2.2开始系统新增了一个缩略图ThumbnailUtils类,位于framework包下的android.media.ThumbnailUtils位置,可以帮助我们从mediaprovider中获取系统中的视频或图片文件的缩略图,该类提供了三种静态方法可以直接调用获取。
1、extractThumbnail (source, width, height):
2、extractThumbnail(source, width, height, options):
3、createVideoThumbnail(filePath, kind):
PS: 此类不向下兼容 转自:http://jakend.iteye.com/blog/1153111
第三部分: Android:指定分辨率和清晰度的图片压缩方法源码
转自:http://www.wizzer.cn/?p=1792
|
[Android算法] bitmap 将图片压缩到指定的大小
最新推荐文章于 2024-05-08 05:20:09 发布