关于javascript:图片裁切全过程解析

39次阅读

共计 1597 个字符,预计需要花费 4 分钟才能阅读完成。

图片裁切过程解析

最近在工作中遇到了一个须要裁剪图片,并将裁剪后图片上传的需要。想着趁这个机会好好梳理下整个图片裁切的过程。

整个裁切次要分两个步骤,一是将裁切的图片用 canvas 画出,二是将 canvas 转换为 file

1. 将裁切的图片用 canvas 画出

// 创立 canvas 元素, image 是 Image 对象, pixelCrop 是裁切的地位(width, height)
function imageToCanvas(image, pixelCrop){var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    
    var maxSize = Math.max(image.width, image.height);
    var safeArea = 2 * ((maxSize/2)* Math.sqrt(2));
    
    canvas.width = safeArea;
    canvas.height = safeArea;
    
    if(ctx !== null){ctx.translate(safeArea / 2, safeArea / 2);
        ctx.translate(-safeArea / 2, -safeArea / 2);
    }
    ctx.drawImage(image, safeArea / 2 - image.width*0.5, safeArea/2 - image.height*0.5);
    
    var data = ctx.getImageData(0, 0, safeArea, safeArea);
    
    canvas.width = pixelCrop.width;
    canvas.height = pixelCrop.height;
    
    ctx.putImageData(data, Math.round(0 - safeArea/2 + image.width*0.5 - pixelCrop.x), Math.round(0 - safeArea/2 + image.height*0.5 - pixelCrop.y));
}

2. 将 canvas 转化为 file(png,jpeg,jpg)

创立一个 canvas
<canvas id="canvas" width="5" height="5"></canvas>
将 canvas 转换为 file(指定 JPEG 格局)

DOM 创立一个新的 img 元素,源图即为 canvas 转换的 file

var canvas = document.getElementById("canvas");

canvas.toBlog(function(blob){var newImg = document.createElement("img");
    var url = URL.createObjectURL(blob);
    
    newImg.onload = function(){
        // no longer need to read the blob so it's revoked
        URL.revokeObjectURL(url);
    };
    
    newImg.src = url;
    document.body.appendChild(newImg);
},"image/jpeg")
罕用 API
// file to url 
objectURL = URL.createObjectURL(object) // object: File 对象、Blob 对象或者 MediaSource 对象

// blob to file
file = new File([myBlob], name, {type: "image/png"}) // A Blob() is almost a File()

// canvas 操作

var ctx = canvas.getContext('2d');
ctx.drawImage(image, width, height);
var data = ctx.getImageData(0, 0, width, height);
ctx.putImageData(data, dx, dy);

正文完
 0