[英]JavaScript: Error from converting user inputed image to base64
嘗試將用戶圖像存儲到服務器。 對此很陌生,所以我剛開始環顧四周,發現以下代碼:
function getBase64Image( imgElem ) {
let canvas = document.createElement( 'canvas' );
canvas.width = imgElem.clientWidth;
canvas.height = imgElem.clientHeight;
let ctx = canvas.getContext( '2d' );
ctx.drawImage(imgElem, 0, 0);
let dataURL = canvas.toDataURL( 'image/png' );
return dataURL.replace( /^data:image\/(png|jpg);base64,/, '' );
}
我正在使用此函數在本地服務器上存儲用戶輸入的圖像,但出現以下錯誤:
factory.js:1 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': 提供的值不是類型 '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'getBase64Image @ factory.js:1SubmitRecipe @ recipe-submission.js :1onclick @ submitrecipe:43
我正在使用type
設置為file
的輸入標簽抓取圖像。 這是我的代碼:
HTML
<label>Image</label>
<span class='err-message' id='image-err'></span></br>
<input type="file" id='image'>
JS
function SubmitRecipe() {
//sets the recipe object and its keys
let recipe = { alias: null, description: null, category: null, instructions: null, image: null };
let img = document.getElementById( 'image' );
recipe.image = JSON.stringify( getBase64Image( img ) );
}
我認為問題與元素image
是HTMLInputElement
的事實有關,而這不是drawImage
期望的。 我只是不知道如何解決它。
感謝所有幫助。
您可以使用 FileReader 對象來執行此操作。 真正巧妙的是它甚至可以首先將數據作為數據 URL 提供給我們 - 這意味着我們不會在此過程中轉換/重新壓縮圖像。 保存為 png 不會放大 jpg,轉換為 jpg 也不會丟失 png 細節。 由於我們不再使用畫布來創建 URL,因此我們不再能夠控制精確的 mime 類型。 因此,我們可能有一個 jpg、png 或 jpeg 文件 - 這只是意味着將|jpeg
添加到正則表達式,因此我們也替換它的實例。
您還可以監聽文件輸入的change
事件。 這樣做將允許您檢查文件的大小和類型以確保它們是可接受的。 (有人可以使用文件輸入選擇一個 100MB 的文本文件)
function byId(id){return document.getElementById(id)} function newEl(tagName){return document.createElement(tagName)} window.addEventListener('load', onDocLoaded, false); function onDocLoaded(evt) { byId('goBtn').addEventListener('click', onBtnClicked, false); } function onBtnClicked(evt) { let imgInput = byId('imageInput'); let chosenFile = imgInput.files[0]; let fr = new FileReader(); fr.onload = function(evt) { var img = newEl('img'); document.body.appendChild(img); img.src = this.result; var dataURL = this.result.replace( /^data:image\\/(png|jpg|jpeg);base64,/, '' ); let recipe = { alias: null, description: null, category: null, instructions: null, image: JSON.stringify(dataURL) }; console.log(recipe); }; fr.readAsDataURL(chosenFile); }
<label>Image</label> <span class='err-message' id='image-err'></span></br> <input type="file" id='imageInput'> <button id='goBtn'>GO</button>
問題是在chrome、fireFox中無法通過input獲取文件路徑,IE8在選擇文件時可以獲取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.