nfnt / resize

Pure golang image resizing
ISC License
3.02k stars 321 forks source link

Don't reverse alpha premultiplication, it's fundamentally wrong #41

Closed e-asphyx closed 8 years ago

e-asphyx commented 8 years ago

I have looked at your code and that's what I have to say: you are fundamentally wrong in dealing with alpha-premultiplied images. Alpha premultiplication was introduced to eliminate interpolation error on images with alpha channel. If image is not premultiplied you shoud premultipy it first before interpolation. Your code does opposite. https://en.wikipedia.org/wiki/Alpha_compositing#Description

nfnt commented 8 years ago

Thanks for having a look into the source code, any feedback is always appreciated! Regarding alpha premultiplication I'm pretty sure that the current approach is okay, but of course I might be wrong there. Could you explain and give me some details and/or code examples on why you think the current approach is wrong?

e-asphyx commented 8 years ago

I wrote a short explanation with some examples in pull request. Get the last greenish sample and try to downsample it to 300x300 px with you favorite image editor. Then compare it to image downsampled by your code and mine. You will see difference.

nfnt commented 8 years ago

Thanks! And sorry, saw your PR after I've written the response. Will check it out ASAP.

e-asphyx commented 8 years ago

Generally speaking alpha channel in not a color channel. It is a pixel's weight which must be taken into account on all linear operations on pixels (both interpolation and alpha blending can be seen as computation of linear combination). https://en.wikipedia.org/wiki/Linear_combination

nfnt commented 8 years ago

But that's only for pre-multiplied alpha, right? Because that's what is done right now: If the image type is using pre-multiplied alpha (e.g. image.RGBA and image.RGBA64) then the RGBA values are transformated to no longer include the alpha-weight in the RGB channels. I.e. I'm reversing the alpha-premultiplication to be able to treat the alpha channel like a color channel afterwards. Otherwise scaling operations on images with translucency will result in slightly off colors (Issue #26 was about that).

nfnt commented 8 years ago

Fixed with PR #42. Thanks @e-asphyx!