I'm trying to resize PNG images, convert them to data URL and then download them in frontend. The whole process works just fine but when I try to open the file (for example) in Photoshop I get "unexpected End of file (EOF)". This only happens when I resize the image using Scalr. When I convert to data URL without any resizing I don't have any problems.
public String designToDataURL(Design design, Integer width, Integer height)
throws IOException {
URL url = new URL(design.getPreviewUrl());
BufferedImage bufferedImage = ImageIO.read(url);
// If I comment this line, everything works quite fine:
BufferedImage resized = Scalr.resize(bufferedImage, width, height);
ByteArrayOutputStream os = new ByteArrayOutputStream();
OutputStream b64 = new Base64.OutputStream(os);
ImageIO.write(bufferedImage, "png", b64);
return os.toString("UTF-8");
}
What am I doing wrong?
EDIT: Using https://www.nayuki.io/page/png-file-chunk-inspector to inspect the PNG chunks.
When you convert to Base64, every aligned block of 3 input bytes become 4 output bytes. Because of this, each input byte partially affects 2 output bytes, so the Base64 encoder cannot generate output bytes on a one-to-one basis; the encoder must buffer some input bytes and write output blocks.
Doing
b64.flush()
will not help due to the partial byte problem. The solution is to dob64.close()
after all input bytes are finished. This will cause remaining partial bytes to be flushed, and it will append the special Base64 termination bytes.