Why does BitmapFactory.decodeByteArray return null?

后端 未结 7 828
失恋的感觉
失恋的感觉 2020-11-28 16:02

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\";
by         


        
相关标签:
7条回答
  • 2020-11-28 16:17

    In my case BitmapFactory.decodeByteArray returned null because received image buffer was incorrect. Try to see sending buffer and incoming buffer, I am sure you will see the difference in two arrays. Most of the time this is the cause.

    0 讨论(0)
  • 2020-11-28 16:21

    You're trying to parse a String as a bitmap. BitmapFactory.decodeByteArray() will fail unless there is a valid bitmap in the byte array. In this case there isn't, so it returns null.

    0 讨论(0)
  • 2020-11-28 16:22

    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.

    0 讨论(0)
  • 2020-11-28 16:22

    Because the bytes in "test".getBytes() doesn't represent a valid bitmap.

    You need to create a byte-array which actually contains an encoded bitmap, not just some "random bytes" corresponding to the representation of a string.

    0 讨论(0)
  • 2020-11-28 16:27

    You get null because you supply invalid bitmap data.

    See documentation of BitmapFactory.decodeByteArray().

    0 讨论(0)
  • 2020-11-28 16:32

    In such case you need to convert the string to Base64 first.

    String strImage = geTImageAsHexString();
    byte[] x = Base64.decode(strImage, Base64.DEFAULT);  //convert from base64 to byte array
    Bitmap bmp = BitmapFactory.decodeByteArray(x,0,x.length);
    
    0 讨论(0)
提交回复
热议问题