文章内容
1、功能需求
在网页中上传一张图片,选择不同的格式,将该图片转换为对应的格式。
2、实现思路
- 通过input上传图片,使用FileReader将文件读取到内存中。
- 将图片转换为canvas,canvas.toDataURL()方法设置为我们需要的格式,如:”image/webp”,”image/jpeg”,”image/png”。
- 最后将canvas转换为图片,显示在网页中。点击右键保存,就得到了不同格式的图片了。
3、toDataURL说明
方法返回一个包含图片展示的 data URI 。可以使用 type 参数其类型,默认为 PNG 格式。图片的分辨率为96dpi。
1)语法
1 | canvas.toDataURL(type, encoderOptions); |
- type:【可选】 图片格式,默认为 image/png,可选格式:”image/webp”,”image/jpeg”,”image/png”。
- encoderOptions:【可选】在指定图片格式为 image/jpeg 或 image/webp的情况下,可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围,将会使用默认值 0.92。其他参数会被忽略。
2)注意点
- 如果画布的高度或宽度是0,那么会返回字符串“data:,”。
- 其中webkit内核浏览器支持“image/webp”类型 。 建议使用Chrome浏览器。
4、代码实现
1)html
1 2 3 4 5 6 7 8 9 | < input type = "file" id = "inputimg" > < select id = "myselect" > < option value = "1" >webp格式</ option > < option value = "2" >jpeg格式</ option > < option value = "3" >png格式</ option > </ select > < button id = "start" >开始转换</ button > < p >预览:</ p > < img id = "imgShow" src = "" alt = "" > |
2)js
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | /*事件*/ document.getElementById( 'start' ).addEventListener( 'click' , function (){ getImg( function (image){ var can = imgToCanvas(image); var imgshow = document.getElementById( "imgShow" ); imgshow.setAttribute( 'src' , canvasToImg(can)); }); }); // 把image 转换为 canvas对象 function imgToCanvas(image) { var canvas = document.createElement( "canvas" ); canvas.width = image.width; canvas.height = image.height; canvas.getContext( "2d" ).drawImage(image, 0, 0); return canvas; } //canvas转换为image function canvasToImg(canvas) { var array=[ "image/webp" , "image/jpeg" , "image/png" ], type=document.getElementById( 'myselect' ).value-1; var src = canvas.toDataURL(array[type]); return src; } //获取图片信息 function getImg(fn){ var imgFile = new FileReader(); try { imgFile.onload = function (e) { var image = new Image(); image.src= e.target.result; //base64数据 image.onload= function (){ fn(image); } } imgFile.readAsDataURL(document.getElementById( 'inputimg' ).files[0]); } catch (e){ console.log( "请上传图片!" +e); } } |