Skip to content

图片旋转

js
/*
 *@functionName: js
 *@params1: imageUrl  图片url
 imageName: 名称
 *@params2: orientation 旋转方向
 *@description: 图片旋转
 *@author: 
 *@date: 2022-01-13 11:38:17
*/
export function rotateImage({ imageUrl, imageName='默认名称', orientation="left" }) {
    let img = new Image()
    img.src = imageUrl
    img.setAttribute("crossOrigin",'Anonymous') // 设置图片跨域
    let canvas = document.createElement("canvas")
    let ctx = canvas.getContext("2d")
    let base64
    let imageFile
    return new Promise((resolve, reject) => {
        img.onload = () => {
            if(img.width > img.height) {
                canvas.width = img.height // 设置canvas的宽高,否则图片大小会不对
                canvas.height = img.width
            }
            if(img.width < img.height) {
                canvas.width = img.height // 设置canvas的宽高,否则图片大小会不对
                canvas.height = img.width
            }
            if(img.width == img.height) {
                canvas.width = img.width // 设置canvas的宽高,否则图片大小会不对
                canvas.height = img.height
            }
            ctx.width = img.width // canvas 图像的宽高
            ctx.height = img.height
            if(orientation == 'left') {
                ctx.rotate(270 * Math.PI / 180);
                ctx.drawImage(img, -img.width, 0);
            }
            if(orientation == 'right') {
                ctx.rotate(90 * Math.PI / 180);
                ctx.drawImage(img, 0, -img.height);
            }
            base64 = canvas.toDataURL("image/png")
            let imageFile = dataURLtoFile(base64, imageName)
            let obj = {
                imageFile: imageFile,
                base64: base64
            }
            resolve(obj)
        }
    })
}

/*
 *@description: 图片base64 转file
 *@author: 
 *@date: 2022-01-12 20:57:29
*/
export function dataURLtoFile(dataUrl, imageName) {
    var arr = dataUrl.split(','),
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
    while(n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], imageName, {
        type: 'image'
    })
}

Released under the MIT License.