Grails: displaying created image in gsp

If you write the bytes to the output stream, you can treat the controller/action as the source of the image in your GSP. Here’s a quick, untested example:

// controller action
def displayGraph = {
    def img // byte array
    //...
    response.setHeader('Content-length', img.length)
    response.contentType="image/png" // or the appropriate image content type
    response.outputStream << img
    response.outputStream.flush()
}

You could then access your image in the src of an <img> tag like this:

<img src="https://stackoverflow.com/questions/4502278/${createLink(controller:"myController', action: 'displayGraph')}"/>

Update:

After reading your question again, this may or may not work – it looks like you might be displaying the graph as the result of a form submission. This will only work if you’re storing the state on the server somewhere (instead of just getting it from the one request where the form is submitted). If you do store enough state on the server to generate the graph, then you’d have to provide some additional parameters to your controller to get the correct image, e.g. src="https://stackoverflow.com/questions/4502278/${g.link(controller:"myController', action: 'displayGraph', params: ['id': 1234])}", where id is how you retrieve the graph state.

Leave a Comment