-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Labels
Description
以下是一个使用 JavaScript 和 Promise 实现的图片格式转换函数,它可以将图片转换为指定的格式(如 JPEG、PNG 等),并返回转换后的结果:
/**
* 图片格式转换函数
* @param {string|File} imageSource - 图片源,可以是 URL 字符串或 File 对象
* @param {string} format - 目标格式,如 'image/jpeg', 'image/png' 等
* @param {number} [quality] - 图片质量(0-1),仅适用于某些格式如 JPEG
* @returns {Promise<Blob>} - 返回一个 Promise,resolve 时返回转换后的 Blob 对象
*/
function convertImageFormat(imageSource, format, quality) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'Anonymous'; // 处理跨域问题(如果是URL)
img.onload = function() {
try {
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// 转换图片格式
canvas.toBlob((blob) => {
if (blob) {
resolve(blob);
} else {
reject(new Error('图片转换失败'));
}
}, format, quality);
} catch (error) {
reject(error);
}
};
img.onerror = function() {
reject(new Error('图片加载失败'));
};
// 处理不同的图片源类型
if (typeof imageSource === 'string') {
img.src = imageSource;
} else if (imageSource instanceof File || imageSource instanceof Blob) {
const reader = new FileReader();
reader.onload = function(e) {
img.src = e.target.result;
};
reader.onerror = function() {
reject(new Error('文件读取失败'));
};
reader.readAsDataURL(imageSource);
} else {
reject(new Error('不支持的图片源类型'));
}
});
}使用示例
// 示例1:使用URL转换图片
convertImageFormat('https://example.com/image.png', 'image/jpeg', 0.8)
.then(blob => {
console.log('转换成功', blob);
// 可以在这里使用 blob,比如创建 URL 或上传
const url = URL.createObjectURL(blob);
document.getElementById('result-image').src = url;
})
.catch(error => {
console.error('转换失败', error);
});
// 示例2:使用文件输入转换图片
document.getElementById('file-input').addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
convertImageFormat(file, 'image/webp')
.then(blob => {
console.log('转换成功', blob);
})
.catch(error => {
console.error('转换失败', error);
});
}
});功能说明
- 支持多种图片源:URL 字符串、File 对象或 Blob 对象
- 可以指定目标格式(如 'image/jpeg', 'image/png', 'image/webp' 等)
- 对于 JPEG 等格式,可以指定质量参数(0-1)
- 使用 Promise 处理异步操作,便于链式调用
- 处理了可能的错误情况(图片加载失败、转换失败等)
这个函数的核心是利用 canvas 的 toBlob 方法来实现格式转换,并通过 Promise 封装异步操作。
yihan12yihan12yihan12