views:

4023

answers:

6

I'm trying to create a thumbnail image on the client side using javascript and a canvas element, but when I shrink the image down, it looks terrible. It looks as if it was downsized in photoshop with the resampling set to 'Nearest Neighbor' instead of Bicubic. I know its possible to get this to look right, because this site can do it just fine using a canvas as well. I've tried using the same code they do as shown in the "[Source]" link, but it still looks terrible. Is there something I'm missing, some setting that needs to be set or something?

EDIT:

I'm trying to resize a jpg. I have tried resizing the same jpg on the linked site and in photoshop, and it looks fine when downsized.

Here is the relevant code:

reader.onloadend = function(e)
{
    var img = new Image();
    var ctx = canvas.getContext("2d");
    var canvasCopy = document.createElement("canvas");
    var copyContext = canvasCopy.getContext("2d");

    img.onload = function()
    {
        var ratio = 1;

        if(img.width > maxWidth)
            ratio = maxWidth / img.width;
        else if(img.height > maxHeight)
            ratio = maxHeight / img.height;

        canvasCopy.width = img.width;
        canvasCopy.height = img.height;
        copyContext.drawImage(img, 0, 0);

        canvas.width = img.width * ratio;
        canvas.height = img.height * ratio;
        ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
    };

    img.src = reader.result;
}

EDIT2:

Seems I was mistaken, the linked website wasn't doing any better of a job of downsizing the image. I tried the other methods suggested and none of them look any better. This is what the different methods resulted in:

Photoshop:

alt text

Canvas:

alt text

Image with image-rendering: optimizeQuality set and scaled with width/height:

alt text

Image with image-rendering: optimizeQuality set and scaled with -moz-transform:

alt text

Canvas resize on pixastic:

alt text

I guess this means firefox isn't using bicubic sampling like its supposed to. I'll just have to wait until they actually add it.

EDIT3:

Original Image

+2  A: 

If you're simply trying to resize an image, I'd recommend setting width and height of the image with CSS. Here's a quick example:

.small-image {
    width: 100px;
    height: 100px;
}

Note that the height and width can also be set using JavaScript. Here's quick code sample:

var img = document.getElement("my-image");
img.style.width = 100 + "px";  // Make sure you add the "px" to the end,
img.style.height = 100 + "px"; // otherwise you'll confuse IE

Also, to ensure that the resized image looks good, add the following css rules to image selector:

As far as I can tell, all browsers except IE using an bicubic algorithm to resize images by default, so your resized images should look good in Firefox and Chrome.

If setting the css width and height doesn't work, you may want to play with a css transform:

If for whatever reason you need to use a canvas, please note that there are two ways an image can be resize: by resizing the canvas with css or by drawing the image at a smaller size.

See this question for more details.

Hope this helps!

Xavi
A: 

Heya, i got this image by right clicking the canvas element in firefox and saving as.

alt text

var img = new Image();
img.onload = function () {
    console.debug(this.width,this.height);
    var canvas = document.createElement('canvas'), ctx;
    canvas.width = 188;
    canvas.height = 150;
    document.body.appendChild(canvas);
    ctx = canvas.getContext('2d');
    ctx.drawImage(img,0,0,188,150);
};
img.src = 'original.jpg';

so anyway, here is a 'fixed' version of your example:

var img = new Image();
// added cause it wasnt defined
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);

var ctx = canvas.getContext("2d");
var canvasCopy = document.createElement("canvas");
// adding it to the body

document.body.appendChild(canvasCopy);

var copyContext = canvasCopy.getContext("2d");

img.onload = function()
{
        var ratio = 1;

        // defining cause it wasnt
        var maxWidth = 188,
            maxHeight = 150;

        if(img.width > maxWidth)
                ratio = maxWidth / img.width;
        else if(img.height > maxHeight)
                ratio = maxHeight / img.height;

        canvasCopy.width = img.width;
        canvasCopy.height = img.height;
        copyContext.drawImage(img, 0, 0);

        canvas.width = img.width * ratio;
        canvas.height = img.height * ratio;
        // the line to change
        // ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
        // the method signature you are using is for slicing
        ctx.drawImage(canvasCopy, 0, 0, canvas.width, canvas.height);
};

// changed for example
img.src = 'original.jpg';
robert
I've tried doing what you did and its not coming out nice like yours. Unless I missed something, the only change you made was to use the scaling method signature instead of the slicing one, right? For some reason its not working for me.
Telanor
A: 

So something interesting that I found a while ago while working with canvas that might be helpful:

To resize the canvas control on its own, you need to use the height="" and width="" attributes (or canvas.width/canvas.height elements). If you use CSS to resize the canvas, it will actually stretch (i.e.: resize) the content of the canvas to fit the full canvas (rather than simply increasing or decreasing the area of the canvas.

It'd be worth a shot to try drawing the image into a canvas control with the height and width attributes set to the size of the image and then using CSS to resize the canvas to the size you're looking for. Perhaps this would use a different resizing algorithm.

It should also be noted that canvas has different effects in different browsers (and even different versions of different browsers). The algorithms and techniques used in the browsers is likely to change over time (especially with Firefox 4 and Chrome 6 coming out so soon, which will place heavy emphasis on canvas rendering performance).

In addition, you may want to give SVG a shot, too, as it likely uses a different algorithm as well.

Best of luck!

mattbasta
Setting the width or height of a canvas via the HTML attributes causes the canvas to be cleared, so there cant be any resizing done with that method. Also, SVG is meant for dealing with mathematical images. I need to be able to draw PNGs and such, so that wont help me out there.
Telanor
+8  A: 

So what do you do if all the browsers (actually, Chrome 5 gave me quite good one) won't give you good enough resampling quality? You implement them yourself then! Oh come on, we're entering the new age of Web 3.0, HTML5 compliant browsers, super optimized JIT javascript compilers, multi-core(†) machines, with tons of memory, what are you afraid of? Hey, there's the word java in javascript, so that should guarantee the performance, right? Behold, the thumbnail generating code:

//returns a function that calculates lanczos weight
function lanczosCreate(lobes){
  return function(x){
    if (x > lobes) 
      return 0;
    x *= Math.PI;
    if (Math.abs(x) < 1e-16) 
      return 1
    var xx = x / lobes;
    return Math.sin(x) * Math.sin(xx) / x / xx;
  }
}

//elem: canvas element, img: image element, sx: scaled width, lobes: kernel radius
function thumbnailer(elem, img, sx, lobes){ 
    this.canvas = elem;
    elem.width = img.width;
    elem.height = img.height;
    elem.style.display = "none";
    this.ctx = elem.getContext("2d");
    this.ctx.drawImage(img, 0, 0);
    this.img = img;
    this.src = this.ctx.getImageData(0, 0, img.width, img.height);
    this.dest = {
        width: sx,
        height: Math.round(img.height * sx / img.width),
    };
    this.dest.data = new Array(this.dest.width * this.dest.height * 3);
    this.lanczos = lanczosCreate(lobes);
    this.ratio = img.width / sx;
    this.rcp_ratio = 2 / this.ratio;
    this.range2 = Math.ceil(this.ratio * lobes / 2);
    this.cacheLanc = {};
    this.center = {};
    this.icenter = {};
    setTimeout(this.process1, 0, this, 0);
}

thumbnailer.prototype.process1 = function(self, u){
    self.center.x = (u + 0.5) * self.ratio;
    self.icenter.x = Math.floor(self.center.x);
    for (var v = 0; v < self.dest.height; v++) {
        self.center.y = (v + 0.5) * self.ratio;
        self.icenter.y = Math.floor(self.center.y);
        var a, r, g, b;
        a = r = g = b = 0;
        for (var i = self.icenter.x - self.range2; i <= self.icenter.x + self.range2; i++) {
            if (i < 0 || i >= self.src.width) 
                continue;
            var f_x = Math.floor(1000 * Math.abs(i - self.center.x));
            if (!self.cacheLanc[f_x]) 
                self.cacheLanc[f_x] = {};
            for (var j = self.icenter.y - self.range2; j <= self.icenter.y + self.range2; j++) {
                if (j < 0 || j >= self.src.height) 
                    continue;
                var f_y = Math.floor(1000 * Math.abs(j - self.center.y));
                if (self.cacheLanc[f_x][f_y] == undefined) 
                    self.cacheLanc[f_x][f_y] = self.lanczos(Math.sqrt(Math.pow(f_x * self.rcp_ratio, 2) + Math.pow(f_y * self.rcp_ratio, 2)) / 1000);
                weight = self.cacheLanc[f_x][f_y];
                if (weight > 0) {
                    var idx = (j * self.src.width + i) * 4;
                    a += weight;
                    r += weight * self.src.data[idx];
                    g += weight * self.src.data[idx + 1];
                    b += weight * self.src.data[idx + 2];
                }
            }
        }
        var idx = (v * self.dest.width + u) * 3;
        self.dest.data[idx] = r / a;
        self.dest.data[idx + 1] = g / a;
        self.dest.data[idx + 2] = b / a;
    }

    if (++u < self.dest.width) 
        setTimeout(self.process1, 0, self, u);
    else 
        setTimeout(self.process2, 0, self);
};
thumbnailer.prototype.process2 = function(self){
    self.canvas.width = self.dest.width;
    self.canvas.height = self.dest.height;
    self.ctx.drawImage(self.img, 0, 0);
    self.src = self.ctx.getImageData(0, 0, self.dest.width, self.dest.height);
    var idx, idx2;
    for (var i = 0; i < self.dest.width; i++) {
        for (var j = 0; j < self.dest.height; j++) {
            idx = (j * self.dest.width + i) * 3;
            idx2 = (j * self.dest.width + i) * 4;
            self.src.data[idx2] = self.dest.data[idx];
            self.src.data[idx2 + 1] = self.dest.data[idx + 1];
            self.src.data[idx2 + 2] = self.dest.data[idx + 2];
        }
    }
    self.ctx.putImageData(self.src, 0, 0);
    self.canvas.style.display = "block";
}

...with which you can produce results like these!

img717.imageshack.us/img717/8910/lanczos358.png

so anyway, here is a 'fixed' version of your example:

img.onload = function() {
  var canvas = document.createElement("canvas");
  new thumbnailer(canvas, img, 188, 3); //this produces lanczos3
  //but feel free to raise it up to 8. Your client will appreciate
  //that the program makes full use of his machine.
  document.body.appendChild(canvas);
}

Now it's time to pit your best browsers out there and see which one will least likely increase your client's blood pressure!

Umm, where's my sarcasm tag?

(since many parts of the code is based on aggen.sourceforge.net is it also covered under GPL2? I dunno)

actually due to limitation of javascript, multi-core is not supported.

syockit
I had actually tried implementing it myself, doing as you did, copying code from an open source image editor. Since I wasn't able to find any solid documentation on the algorithm I had a hard time optimizing it. In the end, mine was kind of slow (took a few seconds to resize the image). When I get the chance, I'll try yours out and see if its any faster. And I think webworkers make multi-core javascript possible now. I was going to try using them to speed it up, but I was having trouble figuring out how to make this into a multithreaded algorithm
Telanor
Looks like you left a piece of the code out. lanczosCreate() seems to be missing. Could you edit your post to include that, so I can test your code out?
Telanor
Sorry, forgot that! I've edited the reply. It's not going to be fast anyways, bicubic should be faster. Not to mention the algorithm I used is not the usual 2-way resizing (which is line by line, horizontal then vertical), so it's a looot slower.
syockit
+1  A: 

I'd highly suggest you check out this link and make sure it is set to true.

Controlling image scaling behavior

Introduced in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0)

Gecko 1.9.2 introduced the mozImageSmoothingEnabled property to the canvas element; if this Boolean value is false, images won't be smoothed when scaled. This property is true by default. view plainprint?

  1. cx.mozImageSmoothingEnabled = false;
Evan Carroll
Yup, its set to true
Telanor
A: 

I know this is an old thread but it might be useful for some people such as myself that months after are hiting this issue for the first time.

Here is some code that resizes the image every time you reload the image. I am aware this is not optimal at all, but I provide it as a proof of concept.

Also, sorry for using jQuery for simple selectors but I just feel too comfortable with the syntax.

        $(function(){

            createImage();

            $(window).resize(function(){createImage();})    

        })  

        var createImage = function(){

            var w = $(window).width();
            var h = $(window).height();
            var canvas = $('#myCanvas').get(0);

            canvas.width = w;               
            canvas.height = h; 

            var context = canvas.getContext('2d');

            img = new Image();              
            img.onload = function(){                                    
                context.drawImage(this,0,0,w,h);
            };
            img.src='http://www.ruinvalor.com/Telanor/images/original.jpg';

        }

My createImage function is called once when the document is loaded and after that it is called every time the window receives a resize event.

Here is the CSS, BTW:

            html, body{
            height: 100%;
            width: 100%;
            margin: 0;
            padding: 0;
            background: #000;
        }
        canvas{
            position: absolute;
            left: 0;
            top: 0;
            z-index: 0;
        }

And here is the HTML:

<html>
    <head>
        <meta charset="utf-8" />
        <title>Canvas Resize</title>
    </head>
    <body>
    <canvas id="myCanvas"></canvas>
    </body>
</html>

I tested it in Chrome 6 and Firefox 3.6, both on the Mac. This "technique" eats processor as it if was ice cream in the summer, but it does the trick.

cesarsalazar