Android编程之图片相关代码集锦

2019-12-10 19:53:55王振洲

11.图片压缩处理:

 

 
  1. /**   * 对图片进行压缩,主要是为了解决控件显示过大图片占用内存造成OOM问题。  
  2. * 一般压缩后的图片大小应该和用来展示它的控件大小相近。   * @param context 上下文  
  3. * @param resId 图片资源Id   * @param reqWidth 期望压缩的宽度  
  4. * @param reqHeight 期望压缩的高度   * @return 压缩后的图片  
  5. */  public static Bitmap compressBitmapFromResourse(Context context, int resId, int reqWidth, int reqHeight) {  
  6. final BitmapFactory.Options options = new BitmapFactory.Options();   /*  
  7. * 第一次解析时,inJustDecodeBounds设置为true,   * 禁止为bitmap分配内存,虽然bitmap返回值为空,但可以获取图片大小  
  8. */  options.inJustDecodeBounds = true;  
  9. BitmapFactory.decodeResource(context.getResources(), resId, options);   final int height = options.outHeight;  
  10. final int width = options.outWidth;   int inSampleSize = 1;  
  11. if (height > reqHeight || width > reqWidth) {   final int heightRatio = Math.round((float) height / (float) reqHeight); 
  12. final int widthRatio = Math.round((float) width / (float) reqWidth);  inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 
  13. }   options.inSampleSize = inSampleSize;  
  14. //使用计算得到的inSampleSize值再次解析图片   options.inJustDecodeBounds = false;  
  15. return BitmapFactory.decodeResource(context.getResources(), resId, options);   }