0

im trying to do a downscale of an image using canvas to later use the data for a hash compare. however i noticed that the canvas (or at least the simple code i use) uses no mipmap filter resulting in very sharp result and makes the test against another existing hash fail (downscaling the image in gimp using linear works as expected). the code i use to downscale is

var canvas = document.createElement("canvas");
canvas.width = width; canvas.height = height;

var context = canvas.getContext('2d');
context.drawImage(image, 0, 0, width, height);

return context.getImageData(0, 0, width, height).data;

this results in this image (left) to the expected (right)

canvas vs gimp

how can i get the canvas to downscale linear?

HellGate
  • 708
  • 1
  • 5
  • 20
  • Currently as far as I know there is no way to control how Canvas scales images. For now, your best bet is to do it manually, i.e. write (or find) your own downscaling algorithm. – jered Mar 23 '16 at 18:22
  • damn thats too bad. i was happy that i found a small and very fast solution and hoped for an option like in opengl or directx. thanks for your info. i will start to work on something now instead of searching for a solution for how i do it now – HellGate Mar 23 '16 at 19:23
  • You can set the context renderer to use smoothing via the flag `ctx.imageSmoothingEnabled = true;` or for firefox `ctx.mozImageSmoothingEnabled = true;`Most hardware configurations that I have used appear to use Bilinear interpolation when this flag is true. – Blindman67 Mar 24 '16 at 01:58
  • i think thats only for upscaling but i tested it anyway with no change sadly – HellGate Mar 24 '16 at 16:14
  • I guess you could create your own pseudo-mipmap -- basically a spritesheet image containing downscaled versions of your image. – markE Mar 24 '16 at 20:10

1 Answers1

1

The new canvas draft specify a way to set re-sampling/interpolation for the canvas. The current method is always bi-linear, or nearest-neighbor if imageSmoothingEnabled = false (both methods are for both up-scaling and down-sampling). The new property is called imageSmoothingQuality:

context . imageSmoothingQuality [ = value ]

The value can be "low", "medium" and "high" (for example something like bi-cubic/Lanczos). However, no browsers has yet implemented this at the moment of writing this and the actual algorithms used for each value is not mandated.

The alternative approaches is to manually re-sample when you need changes above 50% using multiple steps, or to implement a re-sampling algorithm.

Here is an example of multiple steps to achieve bi-cubic quality level (and avoids initial CORS problems), as well as one showing the Lanczos algorithm (need CORS requirements to be met).

In addition to that you can apply sharpening convolution to compensate for some of the lost sharpness.

Community
  • 1
  • 1