2017-01-20 108 views
0

如何將選定的圖像轉換爲base64,然後將其保存在本地存儲中供以後使用。如何將圖像轉換爲base64並將其存儲在本地存儲中

var image = document.getElementById("image"); 
    image.addEventListener('change', function() { 
    //How to 
    }); 
+0

我會用通常的方法轉化爲Base64,並在localStorage的 –

+0

設置vlaue爲什麼不只是保存路徑爲'localStorage'? – Ionut

回答

0

只要看看這個帖子,他們解釋正是你需要的: https://hacks.mozilla.org/2012/02/saving-images-and-files-in-localstorage/

但不是base64編碼,他們提取使用畫布圖像數據+ toDataUrl(),這將從斑點的圖像數據到數據網址。

要小心從外部網站加載的圖像,crossOrigin策略可能會引發安全錯誤。 (見22710627

// Get a reference to the image element 
var elephant = document.getElementById("elephant"); 

// Take action when the image has loaded 
elephant.addEventListener("load", function() { 
    var imgCanvas = document.createElement("canvas"), 
     imgContext = imgCanvas.getContext("2d"); 

    // Make sure canvas is as big as the picture 
    imgCanvas.width = elephant.width; 
    imgCanvas.height = elephant.height; 

    // Draw image into canvas element 
    imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height); 

    // Get canvas contents as a data URL 
    var imgAsDataURL = imgCanvas.toDataURL("image/png"); 

    // Save image into localStorage 
    try { 
     localStorage.setItem("elephant", imgAsDataURL); 
    } 
    catch (e) { 
     console.log("Storage failed: " + e); 
    } 
}, false); 

希望這有助於你:)

+0

確保圖像完全加載之前注入畫布:) –

0

How to convert image into base64 string using javascript

可以使用HTML5吧:

創建一個畫布,你的圖像加載到它,然後用toDataURL()來獲得base64表示(實際上,它是一個data:URL,但它包含base64編碼的圖像)。

然後將此數據保存到lcoalStorage:

localStorage.setItem('imgBase64', this.yourVariable); 
相關問題