Loading dynamically generated images

This is probably a simple question, but I have an API that dynamically generates a PNG image, and I’m not sure how to incorporate it in an Ember app. The idea is that the user sets a bunch of parameters, clicks Submit, and the image renders. Of course, the simple way would just have this in my template:

<img src="{{model.generatedUrl}}">

But the images often take awhile to render (5-10sec), so I want to make use of Ember’s loading states. So is it possible to use a route’s model() to fetch the image (instead of simply generating the URL) and then insert the image data into an <img> tag? Can I even use ember-ajax to retrieve binary data?

My main concern in all of this is that I want a visual indicator that an image is being loaded/rendered, especially if it’s replacing an image that’s already been retrieved.

You can insert the image as base64 data:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />

Something like this should work:

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return new Ember.RSVP.Promise(function(resolve) {
    	const image = new Image()
    	image.onload = function() {
            resolve();
    	}
      
      image.src = "https://unsplash.it/200";
    });
  }
});

You will have to ensure that the correct cache headers are sent with the response, so when you do display the image it doesn’t make another http request.

I hope this helps!

Cheers, Ben

2 Likes

Thanks @nerdyworm! I’m still relatively new to JavaScript in general, and I was unaware of the existence of the Image class (I was confused where you got that class until I googled it). The one thing I had to modify to make your code work was to change resolve(); to resolve(this); so I could use it in my template via {{{model}}}. Other than that, it works as I want it to. Thanks again!