作者:灰灰t2502911555 | 来源:互联网 | 2023-05-19 17:40
Code
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=
即使我给它赋了encoded64 (utf-8)字符串-->aGVsbG8=,它也总是返回null
Why this happening any one have idea..?? What i am doing Wrong can Any one Suggest me...
为什么会发生这种事?我做错了什么,谁能告诉我……
4 个解决方案
1
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. Here's the code to do that:
我认为问题是你试图把一个base64字符串解码成位图,但实际上你只是想把它解码成一个字符串。下面是这样做的代码:
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");