Created
July 26, 2016 07:09
-
-
Save wutianlong/4289e27c8e2a48fe53432b0948ea5567 to your computer and use it in GitHub Desktop.
获取图片指定大小中间,剪裁周边
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 获取中间的方形图片,超出时截取两边 | |
* | |
* @param srcBitmap | |
* @param size 最终正方形的边长 | |
* @return | |
* @throws OutOfMemoryError | |
*/ | |
public static Bitmap getCenterInBitmap(Bitmap srcBitmap, int dstWidth, int dstHeight) { | |
Bitmap finalBm = null; | |
try { | |
if (srcBitmap == null || dstWidth <= 0 || dstHeight <= 0) { | |
return null; | |
} | |
int srcWidth = srcBitmap.getWidth(); | |
int srcHeight = srcBitmap.getHeight(); | |
// 对于没有变化的图片不需要裁切缩放 | |
if (srcWidth == dstWidth && srcHeight == dstHeight) { | |
return srcBitmap; | |
} | |
// 先判断比例相等的 | |
if (dstWidth * srcHeight == dstHeight * srcWidth) { | |
if (dstWidth < srcWidth) { | |
// 仅往小尺寸缩放 | |
Bitmap bm = Bitmap.createScaledBitmap(srcBitmap, dstWidth, dstHeight, true); | |
return bm; | |
} else { | |
return srcBitmap; | |
} | |
} | |
int tmpWidth = 0; | |
int tmpHeight = 0; | |
if (dstWidth * srcHeight > dstHeight * srcWidth) { | |
// 截取上下两部分 | |
if (dstWidth < srcWidth) { | |
// 先对原图进行等比缩放 | |
tmpWidth = dstWidth; | |
tmpHeight = tmpWidth * srcHeight / srcWidth; | |
} | |
} else { | |
// 截取左右两部分 | |
if (dstHeight < srcHeight) { | |
// 先对原图进行等比缩放 | |
tmpHeight = dstHeight; | |
tmpWidth = srcWidth * tmpHeight / srcHeight; | |
} | |
} | |
Bitmap scaleBitmap = null; | |
if (tmpWidth != 0 && tmpHeight != 0) { | |
scaleBitmap = Bitmap.createScaledBitmap(srcBitmap, tmpWidth, tmpHeight, true); | |
} else { | |
scaleBitmap = srcBitmap; | |
} | |
if (scaleBitmap == null) { | |
return null; | |
} | |
int x = 0; | |
int y = 0; | |
int sw = scaleBitmap.getWidth(); | |
int sh = scaleBitmap.getHeight(); | |
int imgWidth = 0; | |
int imgHeight = 0; | |
if (sw * dstHeight < sh * dstWidth) { | |
imgWidth = sw; | |
imgHeight = sw * dstHeight / dstWidth; | |
// 切除上下部分 | |
x = 0; | |
y = (sh - imgHeight) / 2; | |
} else { | |
imgHeight = sh; | |
imgWidth = sh * dstWidth / dstHeight; | |
y = 0; | |
x = (sw - imgWidth) / 2; | |
} | |
if (x == 0 && y == 0) { | |
// 没有缩放的图片 | |
return scaleBitmap; | |
} | |
finalBm = Bitmap.createBitmap(scaleBitmap, x, y, imgWidth, imgHeight); | |
} catch (OutOfMemoryError e) { | |
LogUtils.e(TAG, "getCenterInBitmap OutOfMemoryError :", e); | |
} | |
return finalBm; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment