Вопрос

I have a canvas element in my xhtml. I convert this to a base-64 encoded String called dataUrl with a toDataUrl() call. This produces the following output, truncated for clarity:

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAzQAAAImCAYAAACFG89TAAAgAElEQVR4Xu29C7x/5Zj3 [lots of characters...]"

I want to send this image to my MySQL database. I have a Blob (@Lob) field in my entity, and in order to convert this string to an array of bytes, use dataUrl.getData() and update my entity with this byte array.

In my MySQL database, the BLOB is successfully created. However, when I right-click on it and click Open File in Editor, I see the bytes tab fine but receive a generic error when I click on the image tab, suggesting the bytes are corrupted somehow.

This means that when I want to read this file, using BufferedImage imag = ImageIO.read(is); where is is a ByteArrayInputStream with the bytes array as an argument, imag returns null, more specifically the read method within the BufferedImage class.

Edit: see screenshots, the first is the dataUrl.getBytes() call, the second is the MySQL output.

enter image description here

enter image description here

Это было полезно?

Решение

Instead of String.getBytes(), I used:

BASE64Decoder decoder = new BASE64Decoder();
byte[] b = decoder.decodeBuffer(dataURL.split("^data:image/(png|jpg);base64,")[1]);

And it worked fine.

Другие советы

Okay, it sounds like dataUrl.getData() isn't working for you. The bytes you're storing are basically the ASCII of "data:image/png;base64,iVBORw0KGg..." rather than the binary data stored within the base64 part itself.

It's possible that you're double-encoding this somewhere - it's hard to tell without seeing your code - but that's what we can see so far.

I would suggest that you look at the byte array before you store it in the database. The first few bytes should be 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a. Once you've got that part working, if it still doesn't work you can move forward.

Basically, check the data at every stage of the process, so you can detect the failed-decoding/double-encoding/whatever it is.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top