0

I have a controller hooked up to this method from a GET request:

def renderPNG() {
    URL url = new URL("https://absolute.url.png");
    BufferedImage img = ImageIO.read(url);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(img, "png", baos);
    InputStream is = new ByteArrayInputStream(baos.toByteArray());
    DataInputStream ds = new DataInputStream(is);

    render file: ds, contentType: "image/png"
}

But when I get the image in the response, it is encoded with strange characters. How do I retrieve the image and decode is properly so it can be rendered by a browser?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
dopatraman
  • 13,416
  • 29
  • 90
  • 154

1 Answers1

0

I have solve your problem by converting inputStream to Base64.encode getbyte code from that render it to the Veiw.

def renderPNG () {
 URL url = new URL("http://tineye.com/images/widgets/mona.jpg");
            BufferedImage img = ImageIO.read(url);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(img, "png", baos);
            InputStream is = new  ByteArrayInputStream(baos.toByteArray()); 
      render(Base64.encode(is?.getBytes()))
}

Java script code fetch the image

 /* fetch the user image */
            $.ajax({
                url: "/controller/renderPNG",
                type: 'GET',
                cache: false,
                success: function (result) {
                    document.getElementById('userImage').src = "data:image/png;base64," + result;
                }
            });

HTML code where we want render the image

<div><img id="userImage" src=""alt="User Image"></div>
Dipak Thoke
  • 1,963
  • 11
  • 18