当前位置: 移动技术网 > 移动技术>移动开发>Android > android调用原生图片裁剪后图片尺寸缩放的解决方法

android调用原生图片裁剪后图片尺寸缩放的解决方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

在安卓开发中,如果对拍照后的图片进行图片裁剪,如果是调用系统的裁剪,如下:

/* 
  * 裁剪图片 
  */ 
 private void cropphoto() { 
 
  intent intent = new intent("com.android.camera.action.crop"); 
  uri uri = uri.parse("file://" + picsavepath); 
  intent.setdataandtype(uri, "image/*"); 
  intent.putextra("crop", "true"); 
  // intent.putextra("aspectx", 3); 
  // intent.putextra("aspecty", 2); 
  intent.putextra("outputx", cropx); 
  intent.putextra("outputy", cropy); 
  intent.putextra("scale", "true"); 
  intent.putextra(mediastore.extra_output, uri); 
  intent.putextra("return-data", "false"); 
  intent.putextra("outputformat", bitmap.compressformat.jpeg.tostring()); 
  intent.putextra("nofacedetection", "true"); // no face detection 
  startactivityforresult(intent, crop_picture); 
 } 

这样,就开始对图片进行裁剪了,但是这样会有一个问题,当裁剪框选择的图片与录入的cropx,xropy的形状不同时,比如传入的参数值是个w>h的长方形,而选择框选择的是w<h的长方形时,这样会导致裁剪的图片结果会被压缩变形。

为了解决压缩变形的问题,我的思路是这样的:

1,先对图片进行裁剪,不设置默认的裁剪图片尺寸。

2.对裁剪后的图片再进行图片的缩放。缩放是采角的矩阵的方式进行的缩放

代码如下:

1.

/* 
  * 裁剪图片, 
  */ 
 private void cropphotoandzoom() { 
 
  intent intent = new intent("com.android.camera.action.crop"); 
  uri uri = uri.parse("file://" + picsavepath); 
  intent.setdataandtype(uri, "image/*"); 
  intent.putextra("crop", "true"); 
  intent.putextra("scale", "true"); 
  intent.putextra(mediastore.extra_output, uri); 
  intent.putextra("return-data", "false"); 
  intent.putextra("outputformat", bitmap.compressformat.jpeg.tostring()); 
  intent.putextra("nofacedetection", "true"); // no face detection 
  startactivityforresult(intent, crop_picture_andzoom); 
 } 

2.

/** 
  * 裁剪后,根据裁剪框的长宽比,同时根据图片的需求缩放尺寸进行缩放 
  * 
  * @param path 
  * @param x 
  *   原始的需求尺寸width 
  * @param y 
  *   heiht 
  * @return 
  */ 
 public static bitmap tobigzoom(string path, float x, float y) { 
  log.e("bitmaputil", "path---" + path + "--x--y--" + x + "--" + y); 
  bitmap bitmap = bitmapfactory.decodefile(path); 
  if (bitmap != null) { 
 
   int w = bitmap.getwidth(); 
   int h = bitmap.getheight(); 
   float sx = 0; 
   float sy = 0; 
   if ((float) w / h >= 1) { 
    sx = (float) y / w; 
    sy = (float) x / h; 
    log.e("bitmaputil---", "w/h--->=1"); 
   } else { 
    sx = (float) x / w; 
    sy = (float) y / h; 
    log.e("bitmaputil---", "w/h---<1"); 
   } 
   matrix matrix = new matrix(); 
   matrix.postscale(sx, sy); // 长和宽放大缩小的比例 
   bitmap resizebmp = bitmap.createbitmap(bitmap, 0, 0, w, h, matrix, true); 
   log.e("bitmaputil---", "w---" + resizebmp.getwidth() + "h--" + resizebmp.getheight()); 
   return resizebmp; 
  } 
 
  return null; 
 } 

2中代码,通过判断裁剪框的w,h比来设置图片是放大是横向放大,还是竖向放大,放大后的效果基本上能满足需求。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网