【发布时间】:2013-05-03 09:49:35
【问题描述】:
我可以成功地将给定的 Base64 字符串转换为 Android 中的相应图像。 为了在我的应用程序中测试这个场景,我从我的可绘制文件夹中取出一张图像,并使用这个网站将其转换为相应的 Base64 字符串:Motobit.com。我在这个网站上给出的图像是这样的:
它的尺寸为 23X25 像素,大小为 46.3KB。 在我的 Android 中使用以下代码,我将此图像的 Base64 转换为 Image,如下所示:
byte[] decodedString = Base64.decode(tabData.getString("TabIconImageData"), Base64.DEFAULT);
BitmapFactory.Options options = new Options();
options.inJustDecodeBounds = true;
options.inSampleSize = calculateInSampleSize(options, 500, 500);
options.inJustDecodeBounds = false;
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
myImageView.setImageBitmap(decodedByte);
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
Base64 字符串在图像中已成功转换,但它看起来比原始图像的大小几乎一半。我想要原始大小的图像以及PNG格式的图像。 请指导我解决这个问题。
【问题讨论】:
-
您检查过 calculateInSampleSize 返回的内容吗?
-
@Apfelsaft : 不,我从 Android 开发者网站获得了这个函数来优化位图对象
-
@Apfelsaft : 我调试了我的应用,发现 calculateInSampleSize 返回 1。这是什么意思?
-
这意味着 calculateInSampleSize 不是您的问题的根源。 options.inSampleSize=1 表示读取时不缩放图像。 options.inSampleSize=2 会将图像大小减小一半。
-
虽然它与你的问题无关,但我只是想确保你知道 calculateInSampleSize 在做什么。在您当前的实施中,大于 500x500 的每张图片都会缩小到小于 500x500 的最接近的尺寸。