[英]Decoding base64 String to Bitmap in Android
public Bitmap StringToBitMap(String encodedString){
try{
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}catch(Exception e){
e.getMessage();
return null;
}
}
this always return null even i gave it encoded64 (utf-8) string--->aGVsbG8= 即使我给了它encode64(utf-8)字符串,它也总是返回null-> aGVsbG8 =
Why this happening any one have idea..?? 为什么发生这种情况的任何人都知道.. What i am doing Wrong can Any one Suggest me... 我在做什么错任何人都可以建议我...
I think the problem is that you are trying to decode a base64 string to Bitmap, but actually you just want to decode it to a string. 我认为问题在于您试图将base64字符串解码为Bitmap,但实际上您只想将其解码为字符串。 Here's the code to do that: 这是执行此操作的代码:
String decodeBase64String(String encodedString)
{
byte[] data = Base64.decode(encodedString, Base64.DEFAULT);
return new String(data, "UTF-8");
}
(assumes UTF-8 encoding) (假设采用UTF-8编码)
If you call this function with your test string like this: 如果使用如下测试字符串调用此函数:
String result = decodeBase64String("aGVsbG8=");
then result will be "hello". 那么结果将是“你好”。
Here's how to convert text to a Bitmap: 这是将文本转换为位图的方法:
Bitmap textToBitmap(String text)
{
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStrokeWidth(12);
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
Bitmap bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawText(text, 0, 0, paint);
return bitmap;
}
So you can convert your base64 encoded text to a bitmap like this: 因此,您可以将base64编码的文本转换为如下的位图:
String result = decodeBase64String("aGVsbG8=");
Bitmap bitmap = textToBitmap(result);
Or you could just do this: 或者您可以这样做:
Bitmap bitmap = textToBitmap("hello");
you can revert your code using some other built in methods. 您可以使用其他一些内置方法还原代码。
String base="****Base64 string values of some image******”;
byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView)this.findViewById(R.id.imageView1);
image.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.