読者です 読者をやめる 読者になる 読者になる

Debuginfo

思考とアウトプット

Input type=fileで受け取ったイメージファイルをJavascript/Canvasを使ってリサイズする方法

スケールを合わせたリサイズをCanvasを使って行いました。たかがリサイズ、されどリサイズ。。

$('#imgcapture').change(function(e){
    var image = new Image();
    var reader = new FileReader();
    var file = this.files[0];
    if (!file.type.match(/^image\/(png|jpeg|gif)$/)) return;

    reader.onload = function (event) {
        image.onload = function() {

            //Resize to 800x600
            var width = image.width;
            var height = image.height;
            var chouhen = (width>=height) ? width : height;
            var new_size = 800;  //px
            var canvasheight;
            var canvaswidth;
            if (chouhen < new_size){
                canvaswidth = width;
                canvasheight = height;
            }
            else{
                canvaswidth = parseFloat(new_size)/chouhen * width;
                canvasheight = parseFloat(new_size)/chouhen * height;
            }

            // Create canvas and create resized image
            var canvas0 = document.createElement('canvas');
            canvas0.width = parseInt(canvaswidth);
            canvas0.height = parseInt(canvasheight);
            var context = canvas0.getContext("2d");
            //console.log(image, 0, 0, canvaswidth, canvasheight);
            context.drawImage(image, 0, 0, canvaswidth, canvasheight);
            var resized_img = canvas0.toDataURL("image/jpeg");
            $('#showimg').attr('src', resized_img);
        }
        image.src = event.target.result;
    };
    reader.readAsDataURL(file);
});