Android图片实现压缩处理的实例代码-创新互联
整理文档,搜刮出一个Android图片实现压缩处理的实例代码,稍微整理精简一下做下分享。
目前成都创新互联已为上千家的企业提供了网站建设、域名、网络空间、网站托管、服务器托管、企业网站设计、钟山网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。详解:
1.获取本地图片File文件 获取BitmapFactory.Options对象 计算原始图片 目标图片宽高比 计算输出的图片宽高
2.根据宽高比计算options.inSampleSize值(缩放比例 If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.)得到bitmap位图 根据位图对象获取新的输出位图对象 Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)Creates a new bitmap, scaled from an existing bitmap, whenpossible.
3.获取图片方向调整、失量压缩图片保持在1024kb以下
//进行大小缩放来达到压缩的目的 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(srcImagePath, options); //根据原始图片的宽高比和期望的输出图片的宽高比计算最终输出的图片的宽和高 float srcWidth = options.outWidth; float srcHeight = options.outHeight; float maxWidth = outWidth; float maxHeight = outHeight; float srcRatio = srcWidth / srcHeight; //原始图片宽高比 float outRatio = maxWidth / maxHeight; //目标图片宽高比 float actualOutWidth = srcWidth; float actualOutHeight = srcHeight; if (srcWidth > maxWidth || srcHeight > maxHeight) { if(srcRatio>outRatio){ //原始宽高比大于目标宽高比 actualOutWidth = maxWidth; actualOutHeight = actualOutWidth / srcRatio; }else if(srcRatiomaxFileSize) {//循环判断如果压缩后图片是否大于maxMemmorrySize,大于继续压缩 baos.reset();//重置baos即让下一次的写入覆盖之前的内容 options_ = Math.max(0, options_ - 10);//图片质量每次减少10 actualOutBitmap.compress(Bitmap.CompressFormat.JPEG, options_, baos);//将压缩后的图片保存到baos中 baosLength = baos.toByteArray().length; if (options_ == 0)//如果图片的质量已降到最低则,不再进行压缩 break; } actualOutBitmap.recycle(); //将bitmap保存到指定路径 FileOutputStream fos = null; String filePath = getOutputFileName(srcImagePath); try { fos = new FileOutputStream(filePath); //包装缓冲流,提高写入速度 BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fos); bufferedOutputStream.write(baos.toByteArray()); bufferedOutputStream.flush(); } catch (FileNotFoundException e) { return null; } catch (IOException e) { return null; } finally { if (baos != null) { try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } //获取位图缩放比例 private int computSampleSize(BitmapFactory.Options options, float reqWidth, float reqHeight) { float srcWidth = options.outWidth;//20 float srcHeight = options.outHeight;//10 int sampleSize = 1; if (srcWidth > reqWidth || srcHeight > reqHeight) { int withRatio = Math.round(srcWidth / reqWidth); int heightRatio = Math.round(srcHeight / reqHeight); sampleSize = Math.min(withRatio, heightRatio); } return sampleSize; }
网站题目:Android图片实现压缩处理的实例代码-创新互联
文章URL:http://hbruida.cn/article/ddohhs.html