网页前端方式
// 图片旋转 rotateImg(url, degree) {return new Promise((resolve, reject) => {const suffix = url.match(/[^\.]+$/)[0]const name = url.replace(/(.*\/)*([^.]+).*/ig, '$2').replace(/-\S+/, '')const fileName = `${name}.${suffix}`const img = new Image()img.src = url // 网络路径// img.src = await this.getFileData(file) // 本地上传File对象img.onload = () => {let cvs = document.createElement('canvas')cvs.width = img.heightcvs.height = img.widthlet ctx = cvs.getContext('2d')if (degree == 90) {ctx.rotate(Math.PI / 180 * 90)ctx.drawImage(img, 0, 0, img.width, img.height, 0, -img.height, img.width, img.height)} else if (degree == -90) {ctx.rotate(Math.PI / 180 * -90)ctx.drawImage(img, 0, 0, img.width, img.height, -img.width, 0, img.width, img.height)} else {}const imgBase64 = cvs.toDataURL()const file = this.dataURLtoFile(imgBase64.replace(/-/g, '+').replace(/_/g, '/').replace(/^data:image\/(png|jpeg|jpg);base64,/, ''), fileName, 'image/png')resolve(file)}}) }, // 将网络图片地址转换为File对象 async imageUrlToFile(url, fileName) {const response = await axios.get(url, { responseType: 'arraybuffer' })const imageData = response.dataconst blob = new Blob([imageData], {type: response.headers['content-type']})return new File([blob], fileName, { type: blob.type }) }, // 读取File对象内容 getFileData(file) {return new Promise((resolve, reject) => {const reader = new FileReader()reader.readAsDataURL(file)reader.onload = e => {resolve(e.target.result)}}) }
补充
// 将网络图片地址转换为File对象 async imageUrlToFile(url, fileName) {const response = await axios.get(url, { responseType: 'arraybuffer' })const imageData = response.dataconst blob = new Blob([imageData], {type: response.headers['content-type']})return new File([blob], fileName, { type: blob.type }) }
node端方式
npm install sharp
const sharp = require('sharp');// 旋转图像并保存 sharp('path/to/input/image.jpg').rotate(90).toFile('path/to/output/image.jpg', (err, info) => {if (err) {console.error(err);} else {console.log('图像旋转并保存成功');}});
其他工具包:jimp