image util to handle image file, canvas/image/blob/file translate
copy dist imageFileConvert.umd.js for usage
npm i image-file-convert
import ImageFileConvert from 'image-file-convert'
<inputtype="file" accept="image/*" onchange="fileChange(event)"><scriptsrc="../dist/imageFileConvert.umd.js"></script><script>functionfileChange(ev){letfile=ev.target.files[0];ImageFileConvert.getImageFileData(file,{width: 600,height: 800,cover: false}).then(({ blob, base64 })=>{letimg=ImageFileConvert.blobToImage(blob);img.style.width='300px';console.log(blob,base64.length)document.body.appendChild(img);});}</script>get image file input data, can compress size with option with and height
| 参数 | 类型 | 说明 |
|---|---|---|
| file | file type | 文件类型 |
| option | object | 配置项 |
| width | 宽度 | |
| height | 高度 | |
| cover | 是否覆盖整个区域,默认false |
functionfileChange(ev){letfile=ev.target.files[0];ImageFileConvert.getImageFileData(file,{width: 300,height: 400,cover: true}).then(blob=>{letimg=ImageFileConvert.blobToImage(blob);document.body.appendChild(img);})}blob translate to image, use for ImageFileData() result
| 参数 | 类型 | 说明 |
|---|---|---|
| blob | blob | 二进制文件 |
letimg=ImageFileConvert.blobToImage(blob);file translate to canvas and image, get canvas and image
| 参数 | 类型 | 说明 |
|---|---|---|
| file | file type | 文件类型 |
| option | object | 配置项 |
| width | 宽度 | |
| height | 高度 | |
| cover | 是否覆盖整个区域,默认false |
ImageFileConvert.fileToCanvas(file,{width: 400,height: 400}).then(({ canvas, image })=>{document.body.appendChild(canvas);})file translate to image
| 参数 | 类型 | 说明 |
|---|---|---|
| file | file type | 文件类型 |
ImageFileConvert.fileToImage(file).then(img=>{document.body.appendChild(img);})image translate to canvas
| 参数 | 类型 | 说明 |
|---|---|---|
| img | image element | 图片 |
letcanvas=ImageFileConvert.imageToCanvas(img);canvas tranlate to image, return promise
| 参数 | 类型 | 说明 |
|---|---|---|
| canvas | canvas | canvas |
ImageFileConvert.canvasToImage(cvs,'image/png').then(canvas=>{document.body.append(canvas);})canvas translate to file
letfile=ImageFileConvert.canvasToFile(cvs);canvas to base64
letbase64=ImageFileConvert.canvasToBase64(cvs);image translate to base64
letbase64=ImageFileConvert.imageToBase64(img);rotate image by canvas and return canvas
| 参数 | 类型 | 说明 |
|---|---|---|
| canvas | canvas | 需要绘制的canvs |
| image | img | img元素 |
| degree | int | 角度 |
ImageFileConvert.rotate(cvs,img,degree);