K
K
Kusmich2015-09-29 10:18:56
JavaScript
Kusmich, 2015-09-29 10:18:56

How to put multiple images in local storage?

There is a code that uploads one image to local storage with id="bannerImg", then takes it out of the storage and puts it into the tag with id="tableBanner". But it's not possible to make it possible to have several images, put them in the storage, then take these images and insert them into the c class="tableBanner" tag.

That is, the problem is that it is not possible to process several images at once. For example, take 2 img tags with the class class="bannerImg" they need to be put in storage , and inserted into the img tag with the tableBanner class.

Now in my code (for one image) the bannerImage variable accepts images for further processing. (Conversion to base64, and writing to local storange) but I try the code for several (for example, 2 images instead of id, I refer to the class or tag name), then it does not work wants. For example bannerImage = document.getElementsByClassName('bannerImg1') - doesn't want to work.

Tell me how to solve the problem?

Below is the code for one image:

<img class="tableBanner1" id="bannerImg" crossOrigin="*" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Proton-K-Zarya.jpg/800px-Proton-K-Zarya.jpg" />
<img class="tableBanner1" id="tableBanner" crossOrigin="*" src="" />


 bannerImage = document.getElementById('bannerImg');
 imgData = getBase64Image(bannerImage);
 localStorage.setItem("imgData", imgData);

 function getBase64Image(img) {
     var canvas = document.createElement("canvas");
     canvas.width = img.width;
     canvas.height = img.height;

     var ctx = canvas.getContext("2d");
     ctx.drawImage(img, 0, 0);

     var dataURL = canvas.toDataURL("image/png");

     return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
 }
 var dataImage = localStorage.getItem('imgData');
 bannerImg = document.getElementById('tableBanner');
 bannerImg.src = "data:image/png;base64," + dataImage;


Here's the fiddle: jsfiddle.net/4ra8nhk4/14

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel, 2015-09-29
@Kusmich

I hope you understand that document.getElementsByClassName returns an HTMLCollection and not an array, much less an element

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question