0

When I use HTML5 Canvas' drawImage function, I need to set imageSmoothingEnabled to false, so that enlarged pixels (upscaling) won't blur. However, when reducing the copy (downscaling), some colors appear that weren't present in the original image.

For instance, an upscaled image of Brasília, capital of Brazil. The dark gray represent urban areas. There's only one tone of gray.

vegetation map

Now the same area downscaled (and amplified again, just to make my point clear). As you can see, there are many tones of gray now.

vegetation map

How do I downscale with drawImage without creating any additional color?

Rodrigo
  • 4,706
  • 6
  • 51
  • 94
  • Please provide a [mcve]. Save others the time of recreating the code you wrote to get this far. – Patrick Roberts Jul 30 '19 at 01:38
  • Even your original image has antialias artifacts... – Kaiido Jul 30 '19 at 02:06
  • @Kaiido Where is the answer in the link you provided? I couldn't find it. All I'm seeing is people talking about "image quality", not about "keep the exact original colors". And where are the "artifacts" in my original image? I don't see any! – Rodrigo Jul 30 '19 at 02:13
  • These answers say that what you are doing is "downsampling", which is not covered by the `imageSmoothingEnabled` which only takes care of *interpolation* (creating new pixels). They also offer better ways to downsample than the default average. For the artifacts in your original image: https://jsfiddle.net/Lnhat1fk/ – Kaiido Jul 30 '19 at 02:20
  • @Kaiido Indeed, there are artifacts in the first image, but they're probably caused by PrintScreen on Debian/Gnome, or perhaps by the implementation of canvas by Firefox (which doesn't appear on the internal pixels of the canvas). Otherwise, these artifacts would appear as errors on my application as I move the mouse over the image. That's why I need a different downsampling technique. Thanks for your help. – Rodrigo Jul 30 '19 at 02:38
  • 1
    I agree the linked answers do not cover this. The problem is due to Firefox's implemenatation of `imageSmoothingEnabled=false`. Firefox has chosen to interpolate when scaling down as that is not covered by the specification, while most other browsers will elimate some pixels at regular intervals and preserve the value of those which remain (exactly which rows and columns are lost will differ between browsers). – Mike Sep 04 '22 at 15:00
  • This is important for RGB encoded data such as https://docs.mapbox.com/data/tilesets/guides/access-elevation-data/#response-retrieve-a-terrain-rgb-tile which would be meaningless if R, G and B values were interpolated independently. If possible you should avoid using Firefox, or if it has to be supported you will need to slice up the image to remove excess rows and columns, drawing the final result to a new smaller canvas. – Mike Sep 04 '22 at 15:00

0 Answers0