首頁  >  文章  >  web前端  >  javascript從image轉換為base64位元編碼的String_javascript技巧

javascript從image轉換為base64位元編碼的String_javascript技巧

WBOY
WBOY原創
2016-05-16 16:40:541233瀏覽

最近需要把app的微信分享方法開放給webview,涉及到分享的圖片,如果透過傳送圖片連接,那將要在後台再取一次圖片文件,會影響速度,我選擇webview把image以base64位元編碼的方式傳給本地應用。 以下是實作的參考程式碼:

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
<title>Image to Base64 - jsFiddle demo by handtrix</title> 

<script type='text/javascript' src='//code.jquery.com/jquery-2.0.2.js'></script> 

<link rel="stylesheet" type="text/css" href="/css/result-light.css" rel="external nofollow" > 

<style type='text/css'> 
@import url('//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css'); 

body{ 
padding: 20px; 
} 
</style> 

<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){ 
/** 
* convertImgToBase64 
* @param {String} url 
* @param {Function} callback 
* @param {String} [outputFormat='image/png'] 
* @author HaNdTriX 
* @example 
convertImgToBase64('http://goo.gl/AOxHAL', function(base64Img){ 
console.log('IMAGE:',base64Img); 
}) 
*/ 
function convertImgToBase64(url, callback, outputFormat){ 
var canvas = document.createElement('CANVAS'); 
var ctx = canvas.getContext('2d'); 
var img = new Image; 
img.crossOrigin = 'Anonymous'; 
img.onload = function(){ 
canvas.height = img.height; 
canvas.width = img.width; 
ctx.drawImage(img,0,0); 
var dataURL = canvas.toDataURL(outputFormat || 'image/png'); 
callback.call(this, dataURL); 
// Clean up 
canvas = null; 
}; 
img.src = url; 
} 

$('#img2b64').submit(function(event){ 
var imageUrl = $(this).find('input[name=url]').val(); 
console.log('imageUrl', imageUrl); 
convertImgToBase64(imageUrl, function(base64Img){ 
$('.output') 
.find('textarea') 
.val(base64Img) 
.end() 
.find('a') 
.attr('href', base64Img) 
.text(base64Img) 
.end() 
.find('img') 
.attr('src', base64Img); 
}); 

event.preventDefault(); 
}); 

});//]]> 

</script> 
</head> 
<body> 
<h2>Input</h2> 
<form class="input-group" id="img2b64"> 
<input 
type="url" 
name="url" 
class="form-control" 
placeholder="Insert an IMAGE-URL" 
value="http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png" 
required> 
<span class="input-group-btn"> 
<input 
type="submit" 
class="btn btn-default"> 
</span> 
</form> 
<hr> 
<h2>Output</h2> 
<div class="output"> 
<textarea class="form-control"></textarea><br> 
<a></a><br><br> 
<img><br> 
</div> 
</body> 
</html>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn