Save image as with javascript

How to Save Images To LocalStorage in JavaScript & Load Them

We can save images to localStorage using JavaScript temporarily and load them to the web page without any server. Even if our users don’t have an internet connection, we can get the image from localStorage and display it.

There are 3 steps to store an image in the localStorage in JavaScript:

  • Step 1: Get the image file from the element by listing to the change event.
  • Step 2: Use FileReader() constructor function to convert the image file into a data URL.
  • Step 3: Save the data URL string to localStorage with the setItem() method in JavaScript.

Following these steps, you can save a single image to the localStorage. But if you need to store multiple images, you can do that as well.

After storing the image, you can extract it from the storage and display it on the webpage any time you want with the getItem() method.

Читайте также:  Удалить первое вхождение строки php

I will show you how to store single or multiple images and get them from the localStorage in order to show them on the page.

Save an Image to localStorage in JavaScript

You have seen 3 steps that you need to follow. Now we will discuss those steps in detail with examples.

Step 1: Get an Image File Using The change Event

Before storing an image file, you need to get the file from your user. You can use the element to select a file.

When a user selects an image file, JavaScript fires a change event. You have to listen to that event to get the selected file from the element.

Here I have an element with an id. I can use this id value to grab this element using JavaScript and listen to the change event.

Inside the event callback function, you will have access to the event object with the selected file.

const input = document.getElementById('thumbnail'); input.addEventListener('change', (event) => < const image = event.target.files[0]; >); 

I am using the addEventListener() method to listen to the event. I can get the image file from the target property available in the event object.

You can perform file extension validation in JavaScript to confirm that the selected file is an image.

There are also other file validation methods in JavaScript that you should consider. Like you should check for the file size. Because you can only store between 2 MB to 10 MB in the localStorage.

Step 2: Convert The Image File Into a Data URL

It’s time to convert the image into a data URL after you have the file. Because we can not directly save an image in the localStorage.

You can only store string data in it. The data URL converts the image into a string. JavaScript has the FileReader() constructor function for that.

const input = document.getElementById('thumbnail'); input.addEventListener('change', (event) => < const image = event.target.files[0]; const reader = new FileReader(); reader.readAsDataURL(image); >); 

When we call this constructor function, it returns an object. Now to get the data URL from your image, you need to call the readAsDataURL() method from the reader object.

This method will accept the image file as its argument. Now, you can get the data URL string from the reader object.

Step 3: Save The Data URL String in localStorage

After converting the image file into a string. We will get the string and save it in the localStorage using setItem() method.

When we call the readAsDataURL() method with our image file and the conversion is finished, this method fires the load event.

const input = document.getElementById('thumbnail'); input.addEventListener('change', (event) => < const image = event.target.files[0]; const reader = new FileReader(); reader.readAsDataURL(image); reader.addEventListener('load', () =>< localStorage.setItem('thumbnail', reader.result); >); >); 

You can use the addEventLister() method to listen to the load event. When we get this event it means we have our data ready on the reader object.

Inside the event callback function, we can access the data URL string using the result property in the reader object.

how to save image as data url in localStorage

I am saving that string in the localStorage with the thumbnail key. When you want to get this data from the localStorage, you will use this key.

Load Images From localStorage in JavaScript

You have to access the image stored in the localStorage using the key. When we save anything to the localStorage, we do it as a key/value pair.

When we call the getItem() method by passing a key as its argument, it returns the value associated with that key.

I have a tag without the src value in my HTML file where I want to display the image. Using JavaScript, I will set the src value dynamically.

In the previous section, we stored a single image with the thumbnail key. Let’s see how to get this image and display it on the webpage.

const thumbnail = localStorage.getItem('thumbnail'); const previewImage = document.getElementById('preview'); if (thumbnail) < previewImage.setAttribute('src', thumbnail); >else

I am getting the image data URL from the localStorage by giving the key to the getItem() method.

If the localStorage has the data with the thumbnail key, I will use it as the src value of our tag. But if there is no data in the storage, you can set a default image.

Save an Array of Images in localStorage

In the previous section, you have seen how to store a single image in the localStorage. But you can also select multiple images using the tag.

Therefore you can save an array in the localStorage with multiple images. Let’s see how to do this in this section.

When we select multiple images using the tag, there are a few things that we need to change. Instead of getting a single image file from the target property, we will get all the images.

const input = document.getElementById('thumbnail'); input.addEventListener('change', (event) => < const images = event.target.files; for (const image of images) < const reader = new FileReader(); reader.readAsDataURL(image); reader.addEventListener('load', () => < const imagesArray = localStorage.getItem('images'); let images = []; if (imagesArray) < images = [. JSON.parse(imagesArray)]; images.push(reader.result); >else < images.push(reader.result); >localStorage.setItem('images', JSON.stringify(images)); >); > >); 

It will return an array of image files. You can loop through those files using the for. of statement. You can convert each image file into a data URL inside this loop.

When a data URL is ready, I am getting an array of images from localStorage using the images key in the getItem() method.

If we get the array from the getItem() method, we will parse the value with JSON.parse() method. Because this method will return the array as a string.

Then we will copy the array items in the images array using the spread operator in JavaScript. Now we can push the new data URL to this array from reader.result property.

how to save array of images in localStorage

If there is no previously saved data in the localStorage, we can directly push our new data URL to the images array.

Finally, we can save the images array to our localStorage using setItem() method with the images key. But we have to convert the array into a string with JSON.stringify() method.

const images = JSON.parse(localStorage.getItem('images')); images.forEach((image) => < // Display the image >); 

If you want to display the array of images, you again have to parse the value that getItem() returns using the JSON.parse() method.

Because we converted the array into a string. This method will convert the string into an array. Now you can loop through the array and display the images accordingly.

Conclusion

It is a 3 steps process from getting an image file to saving it to the localStorage. You have seen each of them in detail with code samples.

The main limitation of this process is the storage capacity in the localStorage. You can’t store as many images as you want. It allows data size from 2 MB to 10 MB.

That’s why you should check the file size before saving the image in the localStorage using JavaScript.

Источник

How to Save an HTML Canvas as an Image using JavaScript

How to Save an HTML Canvas as an Image using JavaScript

HTML canvas is a powerful tool for creating graphics and animations.

It can be used to programmatically draw shapes, lines, text, and images on a blank canvas.

A cool thing you can do with a bit of JavaScript is to take the image being rendered on the canvas and download it as an image.

In this post, we’ll learn how to take a HTML canvas image and save it as an image file using JavaScript.

How to save a HTML canvas image as an image file

First, we’ll create a canvas element and draw a circle on it.

Now, we’ll create a button that will download the image.

Attach an event listener to the button that will call a function to download the image.

Now, this is where the magic happens. The key to downloading the canvas as an image is by first creating an anchor link programmatically.

The goal is to take the canvas data, convert it to a base64 encoded string, and set it as the href attribute of the anchor link.

After that, we can programmatically click the link to download the image.

Let’s put the whole thing together now:

That’s it! You can now download the image being rendered on the canvas.

Conclusion

In this post, we learned how to take a HTML canvas image and save it as an image file using JavaScript.

Simply create an anchor link, set the href attribute to the base64 encoded string of the canvas, and programmatically click the link to download the image.

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

Give feedback on this page , tweet at us, or join our Discord !

Источник

Downloading and saving an HTML canvas as an image using Javascript

Downloading and saving an HTML canvas as an image using Javascript

Learn how to allow users to download and save the contents of an HTML canvas in the form of an image.

HTML canvases can be used for a wide variety of applications such as drawing images,

, animation and much more. A particularly useful feature that you can make use of in Javascript is the ability to capture a canvas as an image (formatted to your choice) and allow users to download this image all in one click.

Retrieving and downloading image data from a canvas using Javascript

There are 2 steps involved in allowing users to download an HTML canvas as an image.

First, you must retrieve the image data from the canvas element itself, this can be accomplished using the

function which can be used like so:

var imageData = canvas.toDataURL( type, encoderOptions )

The two arguments are both optional. The type arguments specifies the image format, by default this is set to image/png. The encoderOptions argument specifies the quality of the image which by default is set to 0.92.

Next, you would need to create a temporary link using the data retrieved from the toDataURL() function and automatically activate it so that each step can be incorporated into a single function.

This can be done by assigning the returned value of toDataURL() to the href attribute of an anchor element that you manually create in your Javascript function, this can then be automatically activated using the click() function.

Some browsers will only allow an anchor element to be activated if it resides within the body of your HTML document, to get around this you can temporarily add it to the document, activate the link, then immediately remove it. This will not be visible to the user as it happens almost instantly.

// create temporary link var tmpLink = document.createElement( 'a' ); tmpLink.download = 'image.png'; // set the name of the download file tmpLink.href = imageData; // temporarily add link to body and initiate the download document.body.appendChild( tmpLink ); tmpLink.click(); document.body.removeChild( tmpLink );

This will initiate a download for the canvas image.

Downloading and saving an HTML canvas as an image example

As a quick example for downloading an HTML canvas as an image, we’ll create a new canvas, draw some shapes on it and then use the above code to initiate a download of the canvas image.

Create the HTML canvas and download button:

canvas id="download_canvas" width="210" height="160">canvas>br> button onclick="downloadCanvas()">Download Me! button> 

Initialize the canvas with some basic shapes:

var canvas = document.getElementById( 'download_canvas' ); window.onload = function()< init(); >; function init()< var context = canvas.getContext( '2d' ); context.beginPath(); // draw a blue rectangle context.fillStyle = 'blue'; context.fillRect( 10, 10, 150, 100 ); // draw a red rectangle context.fillStyle = 'red'; context.fillRect( 60, 50, 150, 100 ); >

Create the function to download the image when the download button is clicked:

function downloadCanvas()< // get canvas data var image = canvas.toDataURL(); // create temporary link var tmpLink = document.createElement( 'a' ); tmpLink.download = 'image.png'; // set the name of the download file tmpLink.href = image; // temporarily add link to body and initiate the download document.body.appendChild( tmpLink ); tmpLink.click(); document.body.removeChild( tmpLink ); >

When the download button is clicked, the user should be prompted to download the canvas image:

Downloading a canvas as an image using Javascript example

If you’re having any trouble with the above code or have any general questions feel free to ask them in the comments below!

Christopher Thornton @Instructobit 5 years ago

Источник

Оцените статью