UNPKG

@edifice.io/utilities

Version:
2 lines (1 loc) 1.26 kB
"use strict";class p{static changeDimension(e,n,t,r){return t>r&&(e=Math.round(e*r/t),t=r),e>n&&(t=Math.round(t*n/e),e=n),{height:e,width:t}}static renameFileNameExtension(e,n){const t=e.split(".");return t.pop(),t.join(".")+"."+n}static resizeImage(e,n,t,r,o="jpeg",g=80){const a=g/100,i=document.createElement("canvas"),l=`image/${o}`;let c=e.width,m=e.height;const h=this.changeDimension(m,r,c,t);c=h.width,m=h.height;const s=i.getContext("2d");return s&&(i.width=c,i.height=m,s.fillStyle="white",s.fillRect(0,0,i.width,i.height),s.imageSmoothingEnabled&&s.imageSmoothingQuality&&(s.imageSmoothingQuality="high"),s.drawImage(e,0,0,c,m)),new Promise((w,d)=>{i.toBlob(u=>{u?w(new File([u],n,{type:l,lastModified:new Date().getTime()})):d()},l,a)})}static async resizeImageFile(e,n=1440,t=1440,r=80){if(!e)throw Error("Image resizer: file not found!");if(!e.type||!e.type.startsWith("image/"))throw Error("Image resizer: the file given is not an image.");const o="jpeg";return new Promise(g=>{const a=new Image;a.setAttribute("style","max-width: none;"),a.src=URL.createObjectURL(e),a.onload=async()=>{const i=await this.resizeImage(a,this.renameFileNameExtension(e.name,o),n,t,o,r);g(i)},a.onerror=i=>{throw Error("Image Loading Error: "+i)}})}}module.exports=p;