我有一个位图采取的Base64字符串从我的远程数据库,(encodedImage是字符串表示图像与Base64):
profileImage = (ImageView)findViewById(R.id.profileImage);
byte[] imageAsBytes=null;
try {
imageAsBytes = Base64.decode(encodedImage.getBytes());
} catch (IOException e) {e.printStackTrace();}
profileImage.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
);
profileImage是我的ImageView
但在显示在布局的ImageView中之前,我需要调整图像的大小。我得把它调整到120x120。
有人能告诉我调整大小的代码吗?
我发现的例子不能应用于base64字符串获得位图。
public static Bitmap resizeBitmapByScale(
Bitmap bitmap, float scale, boolean recycle) {
int width = Math.round(bitmap.getWidth() * scale);
int height = Math.round(bitmap.getHeight() * scale);
if (width == bitmap.getWidth()
&& height == bitmap.getHeight()) return bitmap;
Bitmap target = Bitmap.createBitmap(width, height, getConfig(bitmap));
Canvas canvas = new Canvas(target);
canvas.scale(scale, scale);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
canvas.drawBitmap(bitmap, 0, 0, paint);
if (recycle) bitmap.recycle();
return target;
}
private static Bitmap.Config getConfig(Bitmap bitmap) {
Bitmap.Config config = bitmap.getConfig();
if (config == null) {
config = Bitmap.Config.ARGB_8888;
}
return config;
}
保持纵横比,
public Bitmap resizeBitmap(Bitmap source, int width,int height) {
if(source.getHeight() == height && source.getWidth() == width) return source;
int maxLength=Math.min(width,height);
try {
source=source.copy(source.getConfig(),true);
if (source.getHeight() <= source.getWidth()) {
if (source.getHeight() <= maxLength) { // if image already smaller than the required height
return source;
}
double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
int targetWidth = (int) (maxLength * aspectRatio);
return Bitmap.createScaledBitmap(source, targetWidth, maxLength, false);
} else {
if (source.getWidth() <= maxLength) { // if image already smaller than the required height
return source;
}
double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
int targetHeight = (int) (maxLength * aspectRatio);
return Bitmap.createScaledBitmap(source, maxLength, targetHeight, false);
}
}
catch (Exception e)
{
return source;
}
}