簡體   English   中英

返回Javascript中圖像的數據URI Base64字符串的函數

[英]Function that returns the data URI Base64 string of image in Javascript

我真的很努力編寫一個函數來獲取圖像的Base64編碼。 由於此函數將是使用jsPDF.js從網站即時生成PDF的更大腳本的一部分,因此重要的是,能夠將這些Base64編碼作為函數的結果進行計算。 圖像將托管在同一台服務器上,因此沒有相同來源的問題。 我知道canvas元素的.toDataURL()方法可以做到這一點,並且我還知道需要完全加載圖像才能正確獲取數據URL,因此我編寫了此函數

// Encode image to Base64
function encodeBase64(url, format)
{
    var image = new Image(),
    canvas = document.createElement("canvas"),
    context = canvas.getContext("2d");
    image.src = url;
    image.onload = function ()
    {
        canvas.width = image.width;
        canvas.height = image.height;
        context.drawImage(image, 0, 0, image.width, image.height);
        var dataURL = canvas.toDataURL(format);
        alert(dataURL);
    };
}

問題是我不知道如何從onload函數中“提取” dataURL值,以使encodeBase64函數僅返回該值,並且我可以將其放入數組中。 Alert正確返回了該字符串,因此我確定代碼可以工作,但是如果我嘗試編寫任何其他語句,例如“ return dataURL”或類似的語句,則只會得到未定義的值。 請幫忙。

首先將所有圖像加載到數組中。

然后使用畫布創建dataURL,並將dataURL加載到第二個數組中。

示例代碼和演示: http : //jsfiddle.net/m1erickson/fbdb3qbw/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    // array for dataURLs
    var dataURLs=[];

    // put the paths to your images in imageURLs[]
    var imageURLs=[];  
    // push all your image urls!
    imageURLs.push({url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/sun.png",format:null});
    imageURLs.push({url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/temp1.png",format:'image/jpeg'});

    // the loaded images will be placed in images[]
    var imgs=[];

    var imagesOK=0;
    loadAllImages(start);

    function loadAllImages(callback){
        for (var i=0; i<imageURLs.length; i++) {
            var img = new Image();
            img.format=imageURLs[i].format;
            imgs.push(img);
            dataURLs.push('');
            img.index=imgs.length-1;
            img.onload = function(){ 
                imagesOK++; 
                if (imagesOK>=imageURLs.length ) {
                    callback();
                }
            };
            img.onerror=function(){alert("image load failed");} 
            img.crossOrigin="anonymous";
            img.src = imageURLs[i].url;
        }      
    }

    function start(){

        // the imgs[] array now holds fully loaded images
        // the imgs[] are in the same order as imageURLs[]

        // now loop through each img and create its dataURL
        for(var i=0;i<imgs.length;i++){
            var img=imgs[i];
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0, img.width, img.height);
            dataURLs[img.index] = canvas.toDataURL(img.format);    
        }

        // Demo: report the results to the console
        console.log(dataURLs);
    }


}); // end $(function(){});
</script>
</head>
<body>
    <h4>Fetch dataURLs from images (see results in the console)</h4>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

[另外:從textarea中提取網址]

這是從文本區域提取網址的方法。

(#loadImages是當用戶在文本框中輸入網址時按下的按鈕)。

我沒有看過jsPDF來源,所以我無法談談您的dims問題。

$('#loadImages').click(function(){    
    var inputText = document.getElementsByTagName("textarea")[0].value.split("\n");
    for(var i = 0; i < inputText.length; i++){
        imageURLs.push({url: inputText[i],format:"image/jpeg"});
    }    
    loadAllImages(start);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM