跳至主要內容

ImgUtil - 图片工具

会功夫的李白...大约 1 分钟文件图片工具

1. toBlob

将Image转为Blob

参数

序号名称类型含义
1imgHTMLImageElement,Image类型的Html元素图片元素
2type字符串MIME类型,默认image/png

示例

const image = new Image()
image.src = "...";
ImgUtil.toBlob(image).then(res => console.log(res));

2. cut

剪裁图片

参数

序号名称类型含义
1file文件要剪裁的图片文件
2x数字剪裁的x坐标
3y数字剪裁的y轴坐标
4w数字剪裁的宽度
5h数字剪裁的高度
6quality质量图片质量,0到1,默认为1

示例

const input = document.querySelector("#input");
input.onchange = () => {
    const file = input.files[0];
    if (file) {
        try {
            Baitu.ImgUtil.cut(file, 300, 300, 500, 700, 0.5).then(res => {
                console.log(res);
                /*
                * 输出:
                * {
                    "img": {},
                    "file": {},
                    "blob": {},
                    "name": "18061117084733.jpg",
                    "type": "image/jpeg",
                    "quality": 0.5,
                    "params": {
                        "x": 300,
                        "y": 300,
                        "w": 500,
                        "h": 700
                    }
                }
                */
                Baitu.FileUtil.downloadBlob(res.blob, res.name);
            })
        } catch (error) {
            console.error('Error reading file:', error);
        }
    }
};

3. dataURLtoBlob

dataURL转Blob

4. resize

缩放(保持纵横比例)

参数

序号名称类型含义
1file文件要缩放的图片文件
2maxWidth数字最大宽度
3maxHeight数字最大高度
4quality数字质量,0到1,默认1

示例

const input = document.querySelector("#input");
input.onchange = () => {
    const file = input.files[0];
    if (file) {
        try {
            Baitu.ImgUtil.resize(file, 300, 300).then(res => {
                console.log(res)
                /*
                输出:
                {
                    "img": {},
                    "file": {},
                    "blob": {},
                    "name": "18061117084733.jpg",
                    "type": "image/jpeg",
                    "quality": 1,
                    "params": {
                        "maxWidth": 300,
                        "maxHeight": 300
                    }
                }
                */
                Baitu.FileUtil.downloadBlob(res.blob, res.name);
            })
        } catch (error) {
            console.error('Error reading file:', error);
        }
    }
};