本文是我爱模板网亲自实践的两种利用HTML5 CANVAS将图片转成base64格式的方法:
第一种方法,参数是一个img对象:
01 | function getBase64Image(img) { |
02 | var canvas = document.createElement("canvas"); |
03 | canvas.width = img.width; |
04 | canvas.height = img.height; |
06 | var ctx = canvas.getContext("2d"); |
07 | ctx.drawImage(img, 0, 0, img.width, img.height); |
08 | var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase(); |
09 | var dataURL = canvas.toDataURL("image/"+ext); |
第二种方法,在转换的同时,对图片进行了压缩:
01 | function convertImgToBase64(url, callback, outputFormat) { |
02 | var canvas = document.createElement( 'CANVAS' ); |
03 | var ctx = canvas.getContext( '2d' ); |
05 | img.crossOrigin = 'Anonymous' ; |
06 | img.onload = function () { |
07 | var width = img.width; |
08 | var height = img.height; |
10 | var rate = (width < height ? width / height : height / width) / 4; |
11 | canvas.width = width * rate; |
12 | canvas.height = height * rate; |
13 | ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate); |
14 | var dataURL = canvas.toDataURL(outputFormat || 'image/png' ); |
15 | callback.call( this , dataURL); |