引用代码
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function(callback, type, quality) {
var canvas = this
setTimeout(() => {
var binStr = atob(canvas.toDataURL(type, quality).split(',')[1])
var len = binStr.length
var arr = new Uint8Array(len)
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i)
}
callback(new Blob([arr], { type: type || 'image/png' }))
})
}
})
}
/**
* 图片翻转
* @param {object} options 参数
* @param {string} options.content 图像内容
* @param {number} options.rotate 翻转角度
* @example rotateImage({ content: Img, rotate: 90 })
* @returns {Promise<object>} 结果值
*/
const rotateImage = function(options = {}) {
if (!options || typeof options !== 'object') {
throw new Error(`[rotateImage error]: options is not a object`)
}
if (!options.content || (typeof options.content !== 'string' && !(options.content instanceof File))) {
throw new Error(`[rotateImage error]: options.content is not a string or `)
}
if (typeof options.rotate !== 'number') {
throw new Error(`[rotateImage error]: options.rotate is not a number`)
}
return new Promise(resolve => {
const set = (content, type) => {
const canvasDOM = document.createElement('canvas')
const canvasContext = canvasDOM.getContext('2d')
const img = new Image()
img.src = content
img.onload = () => {
canvasDOM.width = img.height
canvasDOM.height = img.width
canvasContext.rotate(options.rotate * Math.PI / 180)
canvasContext.drawImage(img, 0, -img.height, img.width, img.height)
const url = canvasDOM.toDataURL(type, 1)
const callback = blob => {
resolve({ url, blob })
}
canvasDOM.toBlob(callback, type, 1)
}
}
if (options.content instanceof File) {
const fileReader = new FileReader()
fileReader.readAsDataURL(options.content)
fileReader.onload = e => {
set(e.target.result, options.content.type)
}
} else if (typeof options.content === 'string') {
const fileContent = options.content.includes('base64,') ? options.content : `data:image/jpeg;base64,${options.content}`
const fileType =
options.content.includes('data:image/png;base64,') ? 'image/png'
: options.content.includes('data:image/gif;base64,') ? 'image/gif' : 'image/jpeg'
set(fileContent, fileType)
}
})
}
调用方式
const { url, blob } = await rotateImage({
content: 'base64', // 图像base64或file文件
rotate: 90 // 旋转角度
})
console.log('旋转后的base64内容', url)
console.log('旋转后的blob文件', blob)