public static Bitmap zoomIn(Bitmap bitmap, int maxW, int maxH)

时间:2022-12-08 00:44:16

 public static Bitmap zoomIn(Bitmap bitmap, int maxW, int maxH) {
  
  int width  = bitmap.getWidth();
  int height = bitmap.getHeight();
  if (width <= maxW && height <= maxH)
   return bitmap;
  Matrix matrix = new Matrix(); // 创建操作图片用的Matrix对象
  float ratio = (float) getRatio(width, height, maxW, maxH);
  matrix.postScale(ratio, ratio); // 设置缩放比例
//  Bitmap oldbmp = drawable.getBitmap(); // drawable转换成bitmap
  Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); // 建立新的bitmap,其内容是对原bitmap的缩放后的图
  return newbmp; // 把bitmap转换成drawable并返回
 }

 

 

 

private static double getRatio(int srcWidth, int srcHeight, int maxWidth, int maxHeight) {
        double ratio = 0.0;
        double ratio_w = 0.0;
        double ratio_h = 0.0;

        // 按比例计算缩放后的图片大小,maxLength是长或宽允许的最大长度
        if (srcWidth <= maxWidth && srcHeight <= maxHeight) {
            return 0.0;
        }
       
        ratio_w = (double)maxWidth / (double)srcWidth;
        ratio_h = (double)maxHeight / (double)srcHeight;

        if (ratio_w < ratio_h) {
            ratio = ratio_w;
        } else {
            ratio = ratio_h;
        }

        return ratio;
    }