0

I have created the following method, and it builds a base64 encoded string of an image. The issue that I am having is that when this runs, the image that it grabs is high quality but when it is saved into the byte array then encoded, the image is pixelated and fairly low quality, what can I do to get a 100% quality image?

public String getImageString(String img){
    String image = "";
    try{
        BufferedImage bufferedImage = ImageIO.read(HelpPage.class.getResource(img));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "JPG", out);
        String base64bytes = Base64.encode(out.toByteArray());
        image = "data:image/jpeg;base64," + base64bytes;
    }catch(IOException ex){
        Logger.getLogger(HomePage.class.getName()).log(Level.SEVERE, null, ex);
    }
    return image;
}
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • What does the read code look like? Just writing out a base64 version of the binary shouldn't affect the quality at all. – Evan Knowles May 27 '14 at 21:35
  • there is no code... `img` is a image, such as: `/images/myImage.jpg` – Get Off My Lawn May 27 '14 at 21:37
  • @RyanNaddy I think what he means is: How are you reading the encoded text back in and converting it back to an image? – StrongJoshua May 27 '14 at 21:56
  • Try .PNG instead of .JPG – padawan May 27 '14 at 22:10
  • @OnurÇağırıcı Yeah, PNGs are inherently higher quality than JPEGs, but using a JPEG that should not make the image pixelated. – StrongJoshua May 27 '14 at 22:47
  • The default compression when writing JPG images is rather high, which causes the low quality. I posted some snippet in http://stackoverflow.com/a/22812434/3182664 that shows how you can save an image with a quality between 0.0 and 1.0, where 1.0 means that it should hardly be pixelated (but of course, the file size will be larger...) – Marco13 May 27 '14 at 22:50

1 Answers1

1

You don't need to use ImageIO at all here. Just read the bytes from the resource and base64-encode them.

You're converting a JPEG to another JPEG, which is an inherently lossy process, although it shouldn't be as bad as 'low quality'. But you don't need to do it at all.

user207421
  • 305,947
  • 44
  • 307
  • 483