您的位置:首页 > 编程语言

(裁剪只定宽高的图片)一个简单的图片截取代码、等比例、不失真

2013-05-05 14:52 375 查看
直接上干货

/**
* @param rawPath
* 原图地址
* @param dstPath
* 裁剪后地址
* @param width
* 想要的图片宽(宽不能大于高)
* @param height
* 想要的图片高(宽不能大于高)
* */
public static Bitmap cropBitmap(String rawPath, String dstPath, int width,
int height) {
Bitmap bitmap;
Bitmap cropImage = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bitmap = BitmapFactory.decodeFile(rawPath, options);
int rawWidth = options.outWidth;
int rawHeight = options.outHeight;
boolean isWidth = false;

if (rawWidth > width && rawHeight > height) {
// 宽永远小于高
if (rawWidth > rawHeight) {
isWidth = true;
}
MyLog.d("图片宽高", "===========" + rawWidth + "*" + rawHeight);

int inSamplesize = (rawWidth / width) > (rawHeight / height) ? (rawWidth / width)
: (rawHeight / height);

MyLog.d("缩放比例", "===========" + inSamplesize);

options.inJustDecodeBounds = false;
options.inSampleSize = inSamplesize;
bitmap = BitmapFactory.decodeFile(rawPath, options);
Config config = bitmap.getConfig();
config.compareTo(Config.RGB_565);
rawWidth = options.outWidth;
rawHeight = options.outHeight;

MyLog.d("缩放后宽高", "===========" + rawWidth + "*" + rawHeight);
Rect rect = new Rect();
if (isWidth) {
rect.left = ((rawWidth - height) < 0 ? 0 : (rawWidth - height)) / 2;
rect.top = ((rawHeight - width) < 0 ? 0 : (rawHeight - width)) / 2;
rect.right = (rect.left + height) > rawWidth ? rawWidth
: (rect.left + height);
rect.bottom = (rect.top + width) > rawHeight ? rawHeight
: (rect.top + width);
} else {
rect.left = ((rawWidth - width) < 0 ? 0 : (rawWidth - width)) / 2;
rect.top = ((rawHeight - height) < 0 ? 0 : (rawHeight - height)) / 2;
rect.right = (rect.left + width) > rawWidth ? rawWidth
: (rect.left + width);
rect.bottom = (rect.top + height) > rawHeight ? rawHeight
: (rect.top + height);
}

MyLog.d("图片宽高", "===========左" + rect.left + "上" + rect.top + "右"
+ rect.right + "下" + rect.bottom);
cropImage = Bitmap.createBitmap(rect.width(), rect.height(),
config);
Canvas cvs = new Canvas(cropImage);
Rect dr = new Rect(0, 0, rect.width(), rect.height());
cvs.drawBitmap(bitmap, rect, dr, null);
FileUtils.createFile(new File(dstPath),
ImageUtil.bitmap2Bytes(cropImage));
bitmap.recycle();
} else {
File file = new File(rawPath);
byte[] buffer = new byte[(int) file.length()];
try {
new FileInputStream(new File(rawPath)).read(buffer);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileUtils.createFile(new File(dstPath), buffer);
}

return cropImage;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: