K
K
Kusmich2015-09-24 09:28:58
JavaScript
Kusmich, 2015-09-24 09:28:58

How to output image from local storage to img tag?

There is a code that takes an image, encodes it in base64, then sends it to local storage, then gets it. But it’s impossible to get it from local storage and bring it to dom. For example, there is an image with a class , all these actions take place with it (transcoding and sending to the storage), now you need to run through the storage if there are pictures, then display them in the dom (for example, in class="imageActive" ), who did this, tell me how to do it?class="image"

<img id="bannerImg" class="image" crossOrigin="*" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Proton-K-Zarya.jpg/800px-Proton-K-Zarya.jpg" />
<img id="tableBanner" class="image" crossOrigin="*" src="https://upload.wikimedia.org/wikipedia/commons/e/e8/Richard_of_Shrewsbury%2C_1._Duke_of_York.jpg?download" />


var images = document.querySelectorAll('.image');
if (images.length > 0) {
    // в Storage
    var dataArray = [];
    for (var i = 0, itemsLength = images.length; i < itemsLength; i++) {
        dataArray.push({
            img: getBase64Image(images[i]),
            id: images[i].id || ''
        });
    }
 	localStorage.setItem("imagesData", JSON.stringify(dataArray));
    
    //из Storage
    var storageArray = JSON.parse(localStorage.getItem('imagesData'));
    if (Array.isArray(storageArray)) {
        storageArray.map(function (dataImage) {
            var element = document.getElementById(dataImage.id);
            if (element) {
                element.src = "data:image/png;base64," + dataImage.img;
            }
        });
    }
}

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,/, "");
}


There is a full fiddle version: jsfiddle.net/zolotnitskiy/4ra8nhk4/4

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Smirnov, 2015-09-24
@DimaSmirnov

There is a more elegant solution: use the analogue of S3 - ceph. Your method takes 4 times more resources from the server. Try ceph locally to serve content. Just use RadosGW/API.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question