eliot
eliot

Reputation: 1329

Display Dynamic Image in Play! Framework Template

I am creating a Play 2.2 application where depending on the URL, I need to retrieve an image from S3 and render it to the user.

I am aware that I can just render the image after I get it, but I want to embed it in a web page so I can center it and display some more information if necessary.

I see two possible options:

Option A:

Option B: (preferred approach)

Is the second option possible? If so, is it an acceptable approach or would the performance hit not be worth it?

Upvotes: 1

Views: 1046

Answers (1)

biesior
biesior

Reputation: 55798

Disclaimer: It is possible, anyway as your question is rather 'opinion based' - the answer will be also just a suggestion (or rather portion of suggestions).

First, use some graphic library for processing images, i.e. we are using currently GraphicsMagick (GM) + gm4java (sorry, have no idea what is correct lib for Scala) for file cropping, fast, nice, does the job as expected.

In our case we need to avoid the possibility to display origin/cropped images to unauthorized users, therefore we are returning it with Play's return ok(new File(path)) after checking the access rights, but for public assets you can also just use i.e. some HTTP server which will just handle delivering the images or even send cropped images back to S3 and then use it's URL directly in src attribute.

Approach is quite simple:

  • There is some Play action which gets the param(s) like path of original file (that can be translated to use with S3 API)
  • It gets the origin file from S3 (if required) and save it on local HDD for further processing possibilities
  • Use GM to process the file, i.e. crop and resize it, then save it to local HDD or send to special bucket/folder of S3 with unique name
  • Finally it returns the path to file (on S3/HDD) or action (with restrictions) that will return this generated file.
  • You can delete the local copy of the origin right after operation, but also you can leave it there for other options (at least for some time) - and then purge origins older than X days with i.e. scheduler.

Keep in mind that's rather bad (means: slow and expensive) option to fetch S3 file to Play app and processing it every time when there's a request for cropped version, therefore add some additional HDD space into your pricing plan and keep origins and cropped as long as possible at the destination machine.

Also tip: removing color profile (with GM) from result thumbnail(s) will lower it's size so you'll save additional dollars transfer/storage fees.

Upvotes: 1

Related Questions