bitristan
bitristan

Reputation: 650

Why are spots left when converting an RGBA image to RGB?

I converted a png (RGBA) to jpeg (RGB) using libpng to decode the png file and applying png_set_strip_alpha to ignore alpha channels. But after conversion the output image has many spots. I think the reason is that the original image has areas whose alpha was 0, which hides the pixel regardless of its RGB value. And when I strip alpha(ie set alpha = 1), the pixel shows. So I think just using png_set_strip_alpha is not the right solution. Should I write a method myself, or is there already a way to achieve this in libpng?

Upvotes: 2

Views: 1088

Answers (1)

Kornel
Kornel

Reputation: 100170

There is no method for that. If you drop alpha channel libpng will give you raw RGB channels and this will "uncover" colors that were previously invisible.

You should load RGBA image and convert it to RGB yourself. The simplest way is to multiply RGB values by alpha.

This will convert RGBA bitmap to RGB in-place:

for(int i=0; i < width*height; i++) {
   int r = bitmap[i*4+0],
       g = bitmap[i*4+1], 
       b = bitmap[i*4+2], 
       a = bitmap[i*4+3];

   bitmap[i*3+0] = r * a / 255;
   bitmap[i*3+1] = g * a / 255;
   bitmap[i*3+2] = b * a / 255;
}

Upvotes: 3

Related Questions