Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

java - Why does BitmapFactory.decodeByteArray return null?

It's the simple code and instead of getting result to set the Bitmap, I get null. Can anyone tell me where I am making a mistake?

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);

UPDATE

Ok, so I cannot convert text to image like I thought I could. How about this way? Will this create a bitmap?

  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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the documentation:

Returns The decoded bitmap, or null if the image could not be decode.

The bytes involved in the string "test" aren't a valid bitmap, are they?

If you saved the text "test" in a file called foo.png or foo.jpg etc and tried to open it in Windows, what would you expect the result to be? It would be an error: those bytes simply aren't a valid image in any known format.

EDIT: I don't know anything about Android graphics, but your update certainly looks like a much more reasonable way to draw text onto a bitmap.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...