Search code examples
grailsgroovybufferedimage

Grails: write BufferedImage into response


I have ImageController with resize method:

def resize = {
    def pht = Photos.findByTypeAndPhotourl(params.type, params.photourl)
    if (pht != null) {
      BufferedImage source = ImageIO.read(new File(pht.photo))
      ImageResizer imageResizer = new ImageResizer()
      BufferedImage result = imageResizer.resize(source, Integer.parseInt(params.width), Integer.parseInt(params.height))
      imageResizer.writePNG(result, params.name)
      
      render "OK"
    } else {
      render "Error"
    }
  }

As you can see - it writes BufferedImage instance (resized image) on the disk. But I want to return image in response, so resized image will be displayed in browser when user requests resize method (or they will be able to download it). It's smth like file serving problem...

Is this the right way to do it?

ImageIO.write(result, "png", response.getOutputStream())

Solution

  • Yeah, ImageIO is the way to go

    See

    Image resize in Grails