android图片压缩工具类分享
本文实例为大家分享了android图片压缩工具类的具体代码,供大家参考,具体内容如下
importjava.io.BufferedOutputStream; importjava.io.ByteArrayInputStream; importjava.io.ByteArrayOutputStream; importjava.io.File; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importandroid.content.Context; importandroid.graphics.Bitmap; importandroid.graphics.BitmapFactory; importandroid.graphics.BitmapFactory.Options; importandroid.graphics.Matrix; importandroid.net.Uri; importandroid.widget.Toast; /** *圆形图片工具类 * *@authorSKLM * */ publicclassImageViewTool{ /** *我们先看下质量压缩方法 * *@paramimage *@return */ publicstaticBitmapcompressImage(Bitmapimage){ ByteArrayOutputStreambaos=newByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG,100,baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 intoptions=100; while(baos.toByteArray().length/1024>100){//循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset();//重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG,options,baos);//这里压缩options%,把压缩后的数据存放到baos中 options-=10;//每次都减少10 } ByteArrayInputStreamisBm=newByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中 Bitmapbitmap=BitmapFactory.decodeStream(isBm,null,null);//把ByteArrayInputStream数据生成图片 returnbitmap; } /** *图片按比例大小压缩方法(根据路径获取图片并压缩) * *@paramsrcPath *@return */ publicstaticBitmapgetimage(StringsrcPath){ BitmapFactory.OptionsnewOpts=newBitmapFactory.Options(); //开始读入图片,此时把options.inJustDecodeBounds设回true了 newOpts.inJustDecodeBounds=true; Bitmapbitmap=BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空 newOpts.inJustDecodeBounds=false; intw=newOpts.outWidth; inth=newOpts.outHeight; //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为 floathh=800f;//这里设置高度为800f floatww=480f;//这里设置宽度为480f //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 intbe=1;//be=1表示不缩放 if(w>h&&w>ww){//如果宽度大的话根据宽度固定大小缩放 be=(int)(newOpts.outWidth/ww); }elseif(whh){//如果高度高的话根据宽度固定大小缩放 be=(int)(newOpts.outHeight/hh); } if(be<=0) be=1; newOpts.inSampleSize=be;//设置缩放比例 //重新读入图片,注意此时已经把options.inJustDecodeBounds设回false了 bitmap=BitmapFactory.decodeFile(srcPath,newOpts); returncompressImage(bitmap);//压缩好比例大小后再进行质量压缩 } /** *图片按比例大小压缩方法(根据Bitmap图片压缩) * *@paramimage *@return */ publicstaticBitmapcomp(Bitmapimage){ ByteArrayOutputStreambaos=newByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG,100,baos); if(baos.toByteArray().length/1024>1024){//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出 baos.reset();//重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG,30,baos);//这里压缩50%,把压缩后的数据存放到baos中 } ByteArrayInputStreamisBm=newByteArrayInputStream(baos.toByteArray()); BitmapFactory.OptionsnewOpts=newBitmapFactory.Options(); //开始读入图片,此时把options.inJustDecodeBounds设回true了 newOpts.inJustDecodeBounds=true; Bitmapbitmap=BitmapFactory.decodeStream(isBm,null,newOpts); newOpts.inJustDecodeBounds=false; intw=newOpts.outWidth; inth=newOpts.outHeight; //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为 floathh=150f;//这里设置高度为800f floatww=150f;//这里设置宽度为480f //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 intbe=1;//be=1表示不缩放 if(w>h&&w>ww){//如果宽度大的话根据宽度固定大小缩放 be=(int)(newOpts.outWidth/ww); }elseif(w hh){//如果高度高的话根据宽度固定大小缩放 be=(int)(newOpts.outHeight/hh); } if(be<=0) be=1; newOpts.inSampleSize=be;//设置缩放比例 //重新读入图片,注意此时已经把options.inJustDecodeBounds设回false了 isBm=newByteArrayInputStream(baos.toByteArray()); bitmap=BitmapFactory.decodeStream(isBm,null,newOpts); returncompressImage(bitmap);//压缩好比例大小后再进行质量压缩 } publicstaticbyte[]Bitmap2Bytes(Bitmapbm){ ByteArrayOutputStreambaos=newByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG,100,baos); returnbaos.toByteArray(); } /** *按原比例压缩图片到指定尺寸 * *@paramcontext *@paraminputUri *@paramoutputUri *@parammaxLenth *最长边长 */ publicstaticvoidreducePicture(Contextcontext,UriinputUri, UrioutputUri,intmaxLenth,intcompress){ Optionsoptions=newOptions(); options.inJustDecodeBounds=true; InputStreamis=null; try{ is=context.getContentResolver().openInputStream(inputUri); BitmapFactory.decodeStream(is,null,options); is.close(); intsampleSize=1; intlongestSide=0; intlongestSideLenth=0; if(options.outWidth>options.outHeight){ longestSideLenth=options.outWidth; longestSide=0; }else{ longestSideLenth=options.outHeight; longestSide=1; } if(longestSideLenth>maxLenth){ sampleSize=longestSideLenth/maxLenth; } options.inJustDecodeBounds=false; options.inSampleSize=sampleSize; is=context.getContentResolver().openInputStream(inputUri); Bitmapbitmap=BitmapFactory.decodeStream(is,null,options); is.close(); if(bitmap==null){ Toast.makeText(context,"图片获取失败,请确认您的存储卡是否正常", Toast.LENGTH_SHORT).show(); return; } BitmapsrcBitmap=bitmap; floatscale=0; if(longestSide==0){ scale=(float)maxLenth/(float)(srcBitmap.getWidth()); }else{ scale=(float)maxLenth/(float)(srcBitmap.getHeight()); } Matrixmatrix=newMatrix(); matrix.postScale(scale,scale); bitmap=Bitmap.createBitmap(srcBitmap,0,0,srcBitmap.getWidth(), srcBitmap.getHeight(),matrix,true); //如果尺寸不变会返回本身,所以需要判断是否是统一引用来确定是否需要回收 if(srcBitmap!=bitmap){ srcBitmap.recycle(); srcBitmap=null; } saveBitmapToUri(bitmap,outputUri,compress); bitmap.recycle(); bitmap=null; }catch(FileNotFoundExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } privatestaticbooleansaveBitmapToUri(Bitmapbitmap,Uriuri,intcompress) throwsIOException{ Filefile=newFile(uri.getPath()); if(file.exists()){ if(file.delete()){ if(!file.createNewFile()){ returnfalse; } } } BufferedOutputStreamoutStream=newBufferedOutputStream( newFileOutputStream(file)); bitmap.compress(Bitmap.CompressFormat.JPEG,compress,outStream); outStream.flush(); outStream.close(); returntrue; } }
接下来看看第二个写法压缩图片的工具类,如下
importjava.io.ByteArrayInputStream; importjava.io.ByteArrayOutputStream; importjava.io.File; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.IOException; importjava.sql.Date; importjava.text.SimpleDateFormat; importandroid.graphics.Bitmap; importandroid.graphics.Bitmap.Config; importandroid.graphics.BitmapFactory; importandroid.os.Environment; /** *图像压缩工厂类 * *@author * */ publicclassImageFactory{ /** *从指定的图像路径获取位图 * *@paramimgPath *@return */ publicBitmapgetBitmap(StringimgPath){ //Getbitmapthroughimagepath BitmapFactory.OptionsnewOpts=newBitmapFactory.Options(); newOpts.inJustDecodeBounds=false; newOpts.inPurgeable=true; newOpts.inInputShareable=true; //Donotcompress newOpts.inSampleSize=1; newOpts.inPreferredConfig=Config.RGB_565; returnBitmapFactory.decodeFile(imgPath,newOpts); } /** *压缩图片(质量压缩) * *@parambitmap */ publicstaticFilecompressImage(Bitmapbitmap){ ByteArrayOutputStreambaos=newByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 intoptions=100; while(baos.toByteArray().length/1024>500){//循环判断如果压缩后图片是否大于500kb,大于继续压缩 baos.reset();//重置baos即清空baos options-=10;//每次都减少10 bitmap.compress(Bitmap.CompressFormat.JPEG,options,baos);//这里压缩options%,把压缩后的数据存放到baos中 longlength=baos.toByteArray().length; } SimpleDateFormatformat=newSimpleDateFormat("yyyyMMddHHmmss"); Datedate=newDate(System.currentTimeMillis()); Stringfilename=format.format(date); Filefile=newFile(Environment.getExternalStorageDirectory(),filename+".png"); try{ FileOutputStreamfos=newFileOutputStream(file); try{ fos.write(baos.toByteArray()); fos.flush(); fos.close(); }catch(IOExceptione){ e.printStackTrace(); } }catch(FileNotFoundExceptione){ e.printStackTrace(); } recycleBitmap(bitmap); returnfile; } publicstaticvoidrecycleBitmap(Bitmap...bitmaps){ if(bitmaps==null){ return; } for(Bitmapbm:bitmaps){ if(null!=bm&&!bm.isRecycled()){ bm.recycle(); } } } /** *将位图存储到指定的图像路径中 * *@parambitmap *@paramoutPath *@throwsFileNotFoundException */ publicvoidstoreImage(Bitmapbitmap,StringoutPath)throwsFileNotFoundException{ FileOutputStreamos=newFileOutputStream(outPath); bitmap.compress(Bitmap.CompressFormat.JPEG,100,os); } /** *通过像素压缩图像,这将改变图像的宽度/高度。用于获取缩略图 * * *@paramimgPath *imagepath *@parampixelW *目标宽度像素 *@parampixelH *高度目标像素 *@return */ publicBitmapratio(StringimgPath,floatpixelW,floatpixelH){ BitmapFactory.OptionsnewOpts=newBitmapFactory.Options(); //开始读入图片,此时把options.inJustDecodeBounds设回true,即只读边不读内容 newOpts.inJustDecodeBounds=true; newOpts.inPreferredConfig=Config.RGB_565; //Getbitmapinfo,butnoticethatbitmapisnullnow Bitmapbitmap=BitmapFactory.decodeFile(imgPath,newOpts); newOpts.inJustDecodeBounds=false; intw=newOpts.outWidth; inth=newOpts.outHeight; //想要缩放的目标尺寸 floathh=pixelH;//设置高度为240f时,可以明显看到图片缩小了 floatww=pixelW;//设置宽度为120f,可以明显看到图片缩小了 //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 intbe=1;//be=1表示不缩放 if(w>h&&w>ww){//如果宽度大的话根据宽度固定大小缩放 be=(int)(newOpts.outWidth/ww); }elseif(whh){//如果高度高的话根据宽度固定大小缩放 be=(int)(newOpts.outHeight/hh); } if(be<=0) be=1; newOpts.inSampleSize=be;//设置缩放比例 //开始压缩图片,注意此时已经把options.inJustDecodeBounds设回false了 bitmap=BitmapFactory.decodeFile(imgPath,newOpts); //压缩好比例大小后再进行质量压缩 //returncompress(bitmap,maxSize);//这里再进行质量压缩的意义不大,反而耗资源,删除 returnbitmap; } /** *压缩图像的大小,这将修改图像宽度/高度。用于获取缩略图 * * *@paramimage *@parampixelW *targetpixelofwidth *@parampixelH *targetpixelofheight *@return */ publicBitmapratio(Bitmapimage,floatpixelW,floatpixelH){ ByteArrayOutputStreamos=newByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG,100,os); if(os.toByteArray().length/1024>1024){//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出 os.reset();//重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG,50,os);//这里压缩50%,把压缩后的数据存放到baos中 } ByteArrayInputStreamis=newByteArrayInputStream(os.toByteArray()); BitmapFactory.OptionsnewOpts=newBitmapFactory.Options(); //开始读入图片,此时把options.inJustDecodeBounds设回true了 newOpts.inJustDecodeBounds=true; newOpts.inPreferredConfig=Config.RGB_565; Bitmapbitmap=BitmapFactory.decodeStream(is,null,newOpts); newOpts.inJustDecodeBounds=false; intw=newOpts.outWidth; inth=newOpts.outHeight; floathh=pixelH;//设置高度为240f时,可以明显看到图片缩小了 floatww=pixelW;//设置宽度为120f,可以明显看到图片缩小了 //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 intbe=1;//be=1表示不缩放 if(w>h&&w>ww){//如果宽度大的话根据宽度固定大小缩放 be=(int)(newOpts.outWidth/ww); }elseif(w hh){//如果高度高的话根据宽度固定大小缩放 be=(int)(newOpts.outHeight/hh); } if(be<=0) be=1; newOpts.inSampleSize=be;//设置缩放比例 //重新读入图片,注意此时已经把options.inJustDecodeBounds设回false了 is=newByteArrayInputStream(os.toByteArray()); bitmap=BitmapFactory.decodeStream(is,null,newOpts); //压缩好比例大小后再进行质量压缩 //returncompress(bitmap,maxSize);//这里再进行质量压缩的意义不大,反而耗资源,删除 returnbitmap; } /** *按质量压缩,并将图像生成指定的路径 * *@paramimage *@paramoutPath *@parammaxSize *目标将被压缩到小于这个大小(KB)。 *@throwsIOException */ publicvoidcompressAndGenImage(Bitmapimage,StringoutPath,intmaxSize)throwsIOException{ ByteArrayOutputStreamos=newByteArrayOutputStream(); //scale intoptions=100; //Storethebitmapintooutputstream(nocompress) image.compress(Bitmap.CompressFormat.JPEG,options,os); //Compressbyloop while(os.toByteArray().length/1024>maxSize){ //Cleanupos os.reset(); //interval10 options-=10; image.compress(Bitmap.CompressFormat.JPEG,options,os); } //Generatecompressedimagefile FileOutputStreamfos=newFileOutputStream(outPath); fos.write(os.toByteArray()); fos.flush(); fos.close(); } /** *按质量压缩,并将图像生成指定的路径 * *@paramimgPath *@paramoutPath *@parammaxSize *目标将被压缩到小于这个大小(KB)。 *@paramneedsDelete *是否压缩后删除原始文件 *@throwsIOException */ publicvoidcompressAndGenImage(StringimgPath,StringoutPath,intmaxSize,booleanneedsDelete) throwsIOException{ compressAndGenImage(getBitmap(imgPath),outPath,maxSize); //Deleteoriginalfile if(needsDelete){ Filefile=newFile(imgPath); if(file.exists()){ file.delete(); } } } /** *比例和生成拇指的路径指定 * *@paramimage *@paramoutPath *@parampixelW *目标宽度像素 *@parampixelH *高度目标像素 *@throwsFileNotFoundException */ publicvoidratioAndGenThumb(Bitmapimage,StringoutPath,floatpixelW,floatpixelH) throwsFileNotFoundException{ Bitmapbitmap=ratio(image,pixelW,pixelH); storeImage(bitmap,outPath); } /** *比例和生成拇指的路径指定 * *@paramimage *@paramoutPath *@parampixelW *目标宽度像素 *@parampixelH *高度目标像素 *@paramneedsDelete *是否压缩后删除原始文件 *@throwsFileNotFoundException */ publicvoidratioAndGenThumb(StringimgPath,StringoutPath,floatpixelW,floatpixelH,booleanneedsDelete) throwsFileNotFoundException{ Bitmapbitmap=ratio(imgPath,pixelW,pixelH); storeImage(bitmap,outPath); //Deleteoriginalfile if(needsDelete){ Filefile=newFile(imgPath); if(file.exists()){ file.delete(); } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。