[android] bitmap画像を縱橫比固定でリサイズ
目次
bitmap画像を縱橫比固定でリサイズ
bitmap画像を縱橫比固定でリサイズする関数を作成してみた。
縦横長い方を指定サイズに合わせる関数
private static Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {
if (maxHeight > 0 && maxWidth > 0) {
int width = image.getWidth();
int height = image.getHeight();
float ratioBitmap = (float) width / (float) height;
float ratioMax = (float) maxWidth / (float) maxHeight;
int finalWidth = maxWidth;
int finalHeight = maxHeight;
if (ratioMax > 1) {
finalWidth = (int) ((float)maxHeight * ratioBitmap);
} else {
finalHeight = (int) ((float)maxWidth / ratioBitmap);
}
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
return image;
} else {
return image;
}
}
縦横短い方を指定サイズに合わせる関数
private static Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {
if (maxHeight > 0 && maxWidth > 0) {
int width = image.getWidth();
int height = image.getHeight();
float ratioBitmap = (float) width / (float) height;
int finalWidth = maxWidth;
int finalHeight = maxHeight;
if (ratioBitmap > 1) {
finalWidth = (int) ((float)maxHeight * ratioBitmap);
} else {
finalHeight = (int) ((float)maxWidth / ratioBitmap);
}
//トリミングする幅、高さ、座標の設定
int startX = (finalWidth - maxWidth) /2;
int startY = (finalHeight - maxHeight)/2;
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
return mSourceBitmap;
} else {
return image;
}
}
使い方
Bitmap original = BitmapFactory.decodeResource(getResources(),R.drawable.testImage); Bitmap resizedBMP = resize(original, 100,100);
*drawableにtestImageという画像ファイルを配置しておくこと