Search code examples
javacanvasinputstreamjava-2dbytearrayinputstream

Blob corrupt when saving converted Canvas DataURL bytes to database


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


Solution

  • 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.