调整位图的大小,保持宽高比,不会出现失真和裁剪
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了调整位图的大小,保持宽高比,不会出现失真和裁剪相关的知识,希望对你有一定的参考价值。
有没有办法在没有失真的情况下调整Bitmap的大小,使其不超过720 * 1280?较小的高度和宽度是完全正常的(如果宽度或高度较小的情况下空白画布很好)我尝试了这个https://stackoverflow.com/a/15441311/6848469但它给出了扭曲的图像。任何人都能提出更好的解决方案吗?
答案
以下是缩放位图不超过MAX_ALLOWED_RESOLUTION的方法。在你的情况下MAX_ALLOWED_RESOLUTION = 1280
。它将缩小尺寸而不会出现任何失真和质量下降:
private static Bitmap downscaleToMaxAllowedDimension(String photoPath) {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoPath, bitmapOptions);
int srcWidth = bitmapOptions.outWidth;
int srcHeight = bitmapOptions.outHeight;
int dstWidth = srcWidth;
float scale = (float) srcWidth / srcHeight;
if (srcWidth > srcHeight && srcWidth > MAX_ALLOWED_RESOLUTION) {
dstWidth = MAX_ALLOWED_RESOLUTION;
} else if (srcHeight > srcWidth && srcHeight > MAX_ALLOWED_RESOLUTION) {
dstWidth = (int) (MAX_ALLOWED_RESOLUTION * scale);
}
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inDensity = bitmapOptions.outWidth;
bitmapOptions.inTargetDensity = dstWidth;
return BitmapFactory.decodeFile(photoPath, bitmapOptions);
}
如果你已经有BITMAP对象而不是路径,请使用:
private static Bitmap downscaleToMaxAllowedDimension(Bitmap bitmap) {
int MAX_ALLOWED_RESOLUTION = 1024;
int outWidth;
int outHeight;
int inWidth = bitmap.getWidth();
int inHeight = bitmap.getHeight();
if(inWidth > inHeight){
outWidth = MAX_ALLOWED_RESOLUTION;
outHeight = (inHeight * MAX_ALLOWED_RESOLUTION) / inWidth;
} else {
outHeight = MAX_ALLOWED_RESOLUTION;
outWidth = (inWidth * MAX_ALLOWED_RESOLUTION) / inHeight;
}
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, outWidth, outHeight, false);
return resizedBitmap;
}
以上是关于调整位图的大小,保持宽高比,不会出现失真和裁剪的主要内容,如果未能解决你的问题,请参考以下文章
使用Python,OpenCV缩放照片(忽略宽高比,保持宽高比)