js+canvas實現(xiàn)圖片格式webp/png/jpeg在線轉(zhuǎn)換
功能需求:
我們在網(wǎng)頁中上傳一張圖片,選擇不同的格式,將該圖片轉(zhuǎn)換為對應(yīng)的格式。
實現(xiàn)思路:
實現(xiàn)這樣的功能,使用后端語言【php,java等】可以很容易的完成。但是如果只在前端如何完成呢?
1、通過input上傳圖片,使用FileReader將文件讀取到內(nèi)存中。
2、將圖片轉(zhuǎn)換為canvas,canvas.toDataURL()方法設(shè)置為我們需要的格式,如:"image/webp","image/jpeg","image/png"。
3、最后將canvas轉(zhuǎn)換為圖片,顯示在網(wǎng)頁中。點擊右鍵保存,就得到了不同格式的圖片了。
toDataURL說明:
方法返回一個包含圖片展示的 data URI ??梢允褂?type 參數(shù)其類型,默認(rèn)為 PNG 格式。圖片的分辨率為96dpi。
語法:
canvas.toDataURL(type, encoderOptions);
type【可選】 圖片格式,默認(rèn)為 image/png,可選格式:"image/webp","image/jpeg","image/png"。
encoderOptions【可選】在指定圖片格式為 image/jpeg 或 image/webp的情況下,可以從 0 到 1 的區(qū)間內(nèi)選擇圖片的質(zhì)量。如果超出取值范圍,將會使用默認(rèn)值 0.92。其他參數(shù)會被忽略。
注意點:
1、如果畫布的高度或?qū)挾仁?,那么會返回字符串“data:,”。
2、其中webkit內(nèi)核瀏覽器支持“image/webp”類型 。 建議使用Chrome瀏覽器。
代碼例子:
html:
<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">開始轉(zhuǎn)換</button> <p>預(yù)覽:</p> <img id="imgShow" src="" alt="">
js:
/*事件*/
document.getElementById('start').addEventListener('click', function(){
getImg(function(image){
var can=imgToCanvas(image),
imgshow=document.getElementById("imgShow");
imgshow.setAttribute('src',canvasToImg(can));
});
});
// 把image 轉(zhuǎn)換為 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轉(zhuǎn)換為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數(shù)據(jù)
image.onload=function(){
fn(image);
}
}
imgFile.readAsDataURL(document.getElementById('inputimg').files[0]);
}catch(e){
console.log("請上傳圖片!"+e);
}
}
在線Demo:
地址:http://www.dbjr.com.cn/tools/webp.html
說明:需要在chrome瀏覽器中使用,大家可以自行發(fā)揮可以做個批量轉(zhuǎn)換。
到此這篇關(guān)于js+canvas實現(xiàn)圖片格式webp/png/jpeg在線轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)webp/png/jpeg在線轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在Monaco Editor中實現(xiàn)斷點設(shè)置的方法詳解
Monaco Editor 是 vscode 等產(chǎn)品使用的代碼編輯器,功能強(qiáng)大(且復(fù)雜),由微軟維護(hù),本文在 React + TypeScript(Vite)框架下使用 @monaco-editor/react 并介紹開發(fā)斷點顯示時踩到的坑,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2024-04-04
layui的select聯(lián)動實現(xiàn)代碼
今天小編就為大家分享一篇layui的select聯(lián)動實現(xiàn)代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09

