Android:指定分辨率和清晰度的图片压缩方法源码

来源:互联网 发布:编程资料百度云 编辑:程序博客网 时间:2024/06/06 00:16
http://www.wizzer.cn/?p=1792

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. public void transImage(String fromFile, String toFile, int width, int height, int quality)  
  2.     {  
  3.         try  
  4.         {  
  5.             Bitmap bitmap = BitmapFactory.decodeFile(fromFile);  
  6.             int bitmapWidth = bitmap.getWidth();  
  7.             int bitmapHeight = bitmap.getHeight();  
  8.             // 缩放图片的尺寸  
  9.             float scaleWidth = (float) width / bitmapWidth;  
  10.             float scaleHeight = (float) height / bitmapHeight;   
  11.             Matrix matrix = new Matrix();  
  12.             matrix.postScale(scaleWidth, scaleHeight);  
  13.             // 产生缩放后的Bitmap对象  
  14.             Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 00, bitmapWidth, bitmapHeight, matrix, false);  
  15.             // save file  
  16.             File myCaptureFile = new File(toFile);  
  17.             FileOutputStream out = new FileOutputStream(myCaptureFile);  
  18.             if(resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)){  
  19.                 out.flush();  
  20.                 out.close();  
  21.             }  
  22.             if(!bitmap.isRecycled()){  
  23.                 bitmap.recycle();//记得释放资源,否则会内存溢出  
  24.             }  
  25.             if(!resizeBitmap.isRecycled()){  
  26.                 resizeBitmap.recycle();  
  27.             }  
  28.   
  29.         }  
  30.         catch (FileNotFoundException e)  
  31.         {  
  32.             e.printStackTrace();  
  33.         }  
  34.         catch (IOException ex)  
  35.         {  
  36.             ex.printStackTrace();  
  37.         }  
  38.     }  

0 0
原创粉丝点击