keskiviikko 3. huhtikuuta 2013

Reading JPG from disk and rendering it as image/jpeg in Grails

getImage is a controller action, getPictureBytes just reads a file and returns it as a byte array.

def getImage(String filename) {
  def bytes = getPictureBytes(filename)
  response.setContentType('image/jpeg');
  response.outputStream << bytes
}

private getPictureBytes(String filename) throws FileNotFoundException {
 def bytes

 try {
  bytes = new File(grailsApplication.config.picturePath + filename).readBytes()
 } catch (FileNotFoundException e) {
  // If an assigned file was not found, still attempt to return a default image.
  def context = grailsAttributes.getApplicationContext()
  bytes = context.getResource("/images/default-image.jpg").getFile().readBytes()
 }

 bytes
}