Android中3种图片压缩处理方法
Android中图片的存在形式:
1:文件形式:二进制形式存在与硬盘中。
2:流的形式:二进制形式存在与内存中。
3:Bitmap的形式
三种形式的区别:
文件形式和流的形式:对图片体积大小并没有影响。也就是说,如果你手机SD卡上的图片通过流的形式读到内存中,在内存中的大小也是原图的大小。
注意:不是Bitmap的形式。
Bitmap的形式:图片占用的内存会瞬间变大。
以下是代码的形式:
/** *图片压缩的方法总结 */ /* *图片压缩的方法01:质量压缩方法 */ privateBitmapcompressImage(BitmapbeforBitmap){ //可以捕获内存缓冲区的数据,转换成字节数组。 ByteArrayOutputStreambos=newByteArrayOutputStream(); if(beforBitmap!=null){ //第一个参数:图片压缩的格式;第二个参数:压缩的比率;第三个参数:压缩的数据存放到bos中 beforBitmap.compress(CompressFormat.JPEG,100,bos); intoptions=100; //循环判断压缩后的图片是否是大于100kb,如果大于,就继续压缩,否则就不压缩 while(bos.toByteArray().length/1024>100){ bos.reset();//置为空 //压缩options% beforBitmap.compress(CompressFormat.JPEG,options,bos); //每次都减少10 options-=10; } //从bos中将数据读出来存放到ByteArrayInputStream中 ByteArrayInputStreambis=newByteArrayInputStream( bos.toByteArray()); //将数据转换成图片 BitmapafterBitmap=BitmapFactory.decodeStream(bis); returnafterBitmap; } returnnull; } /* *图片压缩方法02:获得缩略图 */ publicBitmapgetThumbnail(intid){ //获得原图 BitmapbeforeBitmap=BitmapFactory.decodeResource( mContext.getResources(),id); //宽 intw=mContext.getResources() .getDimensionPixelOffset(R.dimen.image_w); //高 inth=mContext.getResources().getDimensionPixelSize(R.dimen.image_h); //获得缩略图 BitmapafterBitmap=ThumbnailUtils .extractThumbnail(beforeBitmap,w,h); returnafterBitmap; } /** *图片压缩03 * *@paramid *要操作的图片的大小 *@paramnewWidth *图片指定的宽度 *@paramnewHeight *图片指定的高度 *@return */ publicBitmapcompressBitmap(intid,doublenewWidth,doublenewHeight){ //获得原图 BitmapbeforeBitmap=BitmapFactory.decodeResource( mContext.getResources(),id); //图片原有的宽度和高度 floatbeforeWidth=beforeBitmap.getWidth(); floatbeforeHeight=beforeBitmap.getHeight(); //计算宽高缩放率 floatscaleWidth=0; floatscaleHeight=0; if(beforeWidth>beforeHeight){ scaleWidth=((float)newWidth)/beforeWidth; scaleHeight=((float)newHeight)/beforeHeight; }else{ scaleWidth=((float)newWidth)/beforeHeight; scaleHeight=((float)newHeight)/beforeWidth; } //矩阵对象 Matrixmatrix=newMatrix(); //缩放图片动作缩放比例 matrix.postScale(scaleWidth,scaleHeight); //创建一个新的Bitmap从原始图像剪切图像 BitmapafterBitmap=Bitmap.createBitmap(beforeBitmap,0,0, (int)beforeWidth,(int)beforeHeight,matrix,true); returnafterBitmap; }