为什么 BitmapFactory.decodeByteArray 返回 null?

2022-09-04 05:44:11

这是简单的代码,而不是得到结果来设置位图,我得到null。谁能告诉我我在哪里犯了错误?

String test = "test";
byte[] byteA = test.getBytes();
Bitmap bmp = BitmapFactory.decodeByteArray(byteA, 0, byteA.length); //<- I get null here
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(bmp);

更新

好吧,所以我不能像我想的那样将文本转换为图像。这种方式怎么样?这会创建位图吗?

  Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.RED);
    paint.setTextSize(16);
    paint.setAntiAlias(true);
    paint.setTypeface(Typeface.MONOSPACE);

    Bitmap bm = Bitmap.createBitmap(16, 16, Bitmap.Config.ALPHA_8);
    float x = bm.getWidth();
    float y = bm.getHeight();
    Canvas c = new Canvas(bm);
    c.drawText("Test", x, y, paint);

答案 1

文档中

返回已解码的位图,如果无法解码图像,则为 null。

字符串“test”中涉及的字节不是有效的位图,不是吗?

如果您将文本“test”保存在名为 or etc 的文件中,并尝试在 Windows 中打开它,那么您期望的结果是什么?这将是一个错误:这些字节根本不是任何已知格式的有效图像。foo.pngfoo.jpg

编辑:我对Android图形一无所知,但您的更新肯定看起来像是将文本绘制到位图上的更合理的方式。


答案 2

在这种情况下,您需要先将字符串转换为Base64。

String strImage = geTImageAsHexString();
byte[] x = Base64.decode(strImage, Base64.DEFAULT);  //convert from base64 to byte array
Bitmap bmp = BitmapFactory.decodeByteArray(x,0,x.length);

推荐