Javascript:上传图像文件并调整大小到不同的分辨率然后下载

时间:2016-03-15 12:38:56

标签: javascript jquery html5 image-processing html5-canvas

请为图像处理建议一些库。

我们尝试将图像绘制到画布,然后下载所需大小的图像,但无法实现。

我们希望使用此机制来减少后端服务器中的图像处理

以下是我们尝试的代码

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Image Resize</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form>  
    <input id="filez" type="file" value="img">
    <div id="parentDiv"></div>  
</form>
</body>
<script type="text/javascript">
$(document).ready(function(){

    function ImageResizeObject(parentElement,fileElement,objz){
        this.parentElement = $(parentElement);
        this.fileElement = document.getElementById(fileElement);
        this.objz = objz;
        this.imageFile = this.fileElement.files[0];

        this.parentElement.empty();

        for(var i=0;i<this.objz.length;i++){
            var parentDiv = $("<div></div>");
            parentDiv.attr("id","parentDiv parentDiv"+i);
            var canvas = $("<canvas id='parentDivCanvas"+i+"'></canvas>");
            canvas.css({"height":objz[i].height,"width":this.objz[i].width});
            parentDiv.append(canvas);
            this.parentElement.append(parentDiv);

            var ctx = canvas[0].getContext('2d');
            var img = new Image();          
            img.src =URL.createObjectURL(this.imageFile);                  
            ctx.drawImage(img,0,0,img.width,img.height,0, 0,canvas.width(),canvas.height());

        }
    }

    $("#filez").on('change', function(){
        console.log("file uploaded");
        FileUpload = new ImageResizeObject("#parentDiv","filez",[{"height":"410","width":"410"},{"height":"205","width":"205"}]);                       
    });
});
</script>
</html>

1 个答案:

答案 0 :(得分:1)

在Stackoverflow上,我们不提供图书馆推荐,但是......

您可以使用html5画布调整图片大小。

  • 创建画布元素
  • 将其调整为所需的缩放尺寸
  • 将图像绘制到画布上,缩放到所需大小
  • 使用画布作为image.src
  • 创建一个已调整大小的imageObject

以下是示例代码和演示:

enter image description here

&#13;
&#13;
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/marioRunningRight1.png";
function start(){
    resizeImg(img,0.50);
    resizeImg(img,2);
}

function resizeImg(img,scaleFactor){
    var c=document.createElement('canvas');
    var ctx=c.getContext('2d');
    var iw=img.width;
    var ih=img.height;
    c.width=iw*scaleFactor;
    c.height=ih*scaleFactor;
    ctx.drawImage(img,0,0,iw*scaleFactor,ih*scaleFactor);
    var scaledImg=new Image();
    scaledImg.onload=function(){
        // scaledImg is a scaled imageObject for upload/download
        // For testing, just append it to the DOM
        document.body.appendChild(scaledImg);
    }
    scaledImg.src=c.toDataURL();
}
&#13;
<h4>Original image</h4>
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/marioRunningRight1.png' crossOrigin='anonymous'>
<br>
<h4>Resized images at 50% and at 200%</h4>
&#13;
&#13;
&#13;