1. 程式人生 > >jquery將圖片轉換成base64格式字串

jquery將圖片轉換成base64格式字串

<script>
    /**
		 * 將圖片轉換為Base64
		 */
		function image2Base64(img) {
		    var canvas = document.createElement("canvas");
		    canvas.width = img.width;
		    canvas.height = img.height;
		    var ctx = canvas.getContext("2d");
		    ctx.drawImage(img, 0, 0, img.width, img.height);
		    var dataURL = canvas.toDataURL("image/png");
		    return dataURL;
		}

        $("#tijiao").click(function(){

            var imgurl = $(".z_addImg img").attr("src");  //獲取的圖片路徑


		    var img = new Image();

		    img.src=imgurl;
		 
	        var base64 = image2Base64(img);

	      	alert(base64);   //彈出base64圖片字串看看,如果很長很長就成功啦
        })
</script>