压缩bitmap算法
2016-06-30 15:47
357 查看
public static Bitmap decodeFile(File f) { try { // decode image size BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // BitmapFactory.decodeStream(new FileInputStream(f), null, options); int inSampleSize = computeSampleSize(options, -1, 128 * 128); // decode with inSampleSize options.inSampleSize = inSampleSize; options.inJustDecodeBounds = false; return BitmapFactory.decodeStream(new FileInputStream(f), null, options); } catch (Exception e) { } return null; } public static void copyStream(InputStream is, OutputStream os) { final int buffer_size = 1024; try { byte[] bytes = new byte[buffer_size]; for (;;) { int count = is.read(bytes, 0, buffer_size); if (count == -1) break; os.write(bytes, 0, count); } } catch (Exception ex) { ex.printStackTrace(); } } /** * 根据实际需要,计算出合适的inSampleSize,以减少内存的开销 * * @param options * @param minSideLength 最小长度,不限制则为-1 * @param maxNumOfPixels 最大像素点,128 * 128 * @return */ public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels); int roundedSize; if (initialSize <= 8) { roundedSize = 1; while (roundedSize < initialSize) { roundedSize <<= 1; } } else { roundedSize = (initialSize + 7) / 8 * 8; } return roundedSize; } private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; //ceil get the integer number >parameter int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math .sqrt(w * h / maxNumOfPixels)); int upperBound = (minSideLength == -1) ? 128 : (int) Math.min( Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) { // return the larger one when there is no overlapping zone. return lowerBound; } if ((maxNumOfPixels == -1) && (minSideLength == -1)) { return 1; } else if (minSideLength == -1) { return lowerBound; } else { return upperBound; } }
相关文章推荐
- $.ajax()方法详解
- opencv 界面画框
- python字符串拼接
- Android proguard 代码混淆
- 如何在神箭手云爬虫上运行爬虫
- EffectiveJava-通用程序设计
- Response.cookies和Request.cookies
- linux Socket 中 setsockopt的SO_KEEPALIVE选项
- Mount.cifs cannot allocate memory mounting Windows share
- RedHat6.5系统Oracle11gR2数据库安装教程(可用版)
- 电脑端用于检测网络状态
- 虚拟化基础架构Windows 2008篇之9-配置Windows部署服务
- rxJava例子
- webstrom配置
- java.lang.RuntimeException: Your content must have a TabHost whose id attribute is 'android.R.id.ta
- DOS常用命令
- 浅谈HTTP中Get与Post的区别
- 随堂笔记(一)--指针与数组
- 记mvc:resources配置和后台restful接口访问问题
- Debian配置JDK1.7 与Linux Java Helloworld