Question

I've read several articles/stackoverflow's questions about resizing images in order to upload them. But I did'nt found a function like this:

function resize(src,maxWidth, max Height){
    // some staff, creating a new Canvas and drawing the src inside
    return canvas;
}

Until now, I've only seen piece of code like :

var img = new Image();
img.src=src
img.onload(function(){
    // Creating a Canvas here and do all the needed operations with the Canvas...
}

In this case, I don't see how to get the created Canvas.

Was it helpful?

Solution

Here is the outline of your resize function:

  • create a new canvas with document.createElement("canvas") and a context for the canvas.
  • create a new Image object and set its .src
  • create a .onload for the new image that draws the resized image to the canvas using drawImage.
  • return the new canvas element

Example code and a Demo: http://jsfiddle.net/m1erickson/UTjW8/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var imageSource="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/faces.png";

    var canvas=resize(imageSource,125,125);

    document.body.appendChild(canvas);


    // scale an image to canvas maintaining an aspect ratio
    function resize(srcURL,maxWidth,maxHeight){
        var tcanvas=document.createElement("canvas");
        var tctx=tcanvas.getContext("2d");
        var img=new Image();
        img.onload=function(){
            var iw=img.width;
            var ih=img.height;
            var ratio = Math.min(maxWidth/iw,maxHeight/ih);
            tcanvas.width=iw*ratio;
            tcanvas.height=ih*ratio;
            tctx.drawImage(img,0,0,iw,ih,0,0,iw*ratio,ih*ratio);
        }
        img.src=srcURL;
        return(tcanvas);
     }

}); // end $(function(){});
</script>
</head>
<body>
</body>
</html>

OTHER TIPS

to create a canvas all you have to do is this

var canvas = document.createElement('canvas');
canvas.width = yourwidth;
canvas.height = yourheight;

if you are not asking how to create element just tell me and I'll change the answer

I encountered this problem a week ago. I have tried many methods and finally found solely one method. You can you a uploader which crops & resizes the image and uploads it the to server. The basic idea is that resize the image in the canvas, convert the canvas to a blob for uploading, then upload it in the form. The detailed process is complicated, so there is no free plugin right now.

However, there is a cheap plugin Crop & Upload which can solve your problem easily. I already use it in my website and it runs pretty well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top