Tech Blog

Save an Image in Cloud Apps User Settings

The Cloud App framework provides the ability for an app to persist data at the user (settings) or institution (configuration) level. The data is stored as a JSON blob and thus can contain standard JavaScript types such as strings, numbers, booleans, and arrays. But what if the developer wishes to provide the opportunity to store an image, for example a logo? In that case, we can use standard JavaScript features to store a textual representation of the image and use it elsewhere in our app. In this post, we’ll show how to prompt a user to specify an image, resize it, turn it into a base64 representation, and store it in settings. We’ll also retrieve a previously stored image and display it on the screen.

First we’ll define a new Angular component, and in the HTML we’ll provide an input of type file, with a change event that points to a function in our .ts file. In the fileChangeEvent function, we call a method to resize the image. This is to ensure the user doesn’t provide an image which is too large and takes too long to load. We’ve defined a constant which specifies the max size for the image depending on our requirements. The resize function does the following:

  • Creates a FileReader object to load the provided image file into memory as a “data URL“, which “represents the file’s data as a base64-encoded string”
  • Loads the result into a JavaScript Image object in order to retrieve the height and width
  • Creates a Canvas to draw the newly resized image
  • Returns the contents of the canvas as a data URL

With the image resized and in a text format, we can now save the result to a regular JavaScript object, and save the object to settings.

All that remains is to display the image in an img tag. To do so, we simply add a tag to our component HTML and set the src to the data URL which is saved in our settings:

<img src="{{settings.logo}}" style="max-width: 100%;"/>

The result is a component which both displays the saved image and allows users to update it. Of course, the image can be displayed on any component by retrieving the saved settings and using the same methodology.

The full code for this example is available in this gist.

Leave a Reply