Author Topic: converting rgb bmp with alpha channel to gray leads to wrong pixel values  (Read 88 times)

Offline heju

  • Imaging User
  • *
  • Posts: 4
    • View Profile

when converting a rgb bmp with alpha channel to ifGray8, I noted that the pixel values in the final image are not as expected.

I think the problem could be here:
The source is read using PColor24Rec(Src), however in memory there is the alpha byte first (not the blue byte). Therefore the alpha channel is interpreted as blue channel. As the Src is incremented by 4 which is correct, the pixels do not get mixed up totally. 

Code: [Select]
procedure ChannelToGray(NumPixels: LongInt; Src, Dst: PByte; SrcInfo,
  DstInfo: PImageFormatInfo);
  I: LongInt;
  Pix64: TColor64Rec;
  Alpha: Word;
  // two most common conversions (R8G8B8->Gray8 nad A8R8G8B8->Gray8)
  // are made separately from general conversions to make them faster
  if (SrcInfo.BytesPerPixel in [3, 4]) and (DstInfo.Format = ifGray8) then
    for I := 0 to NumPixels - 1 do
      Dst^ := Round(GrayConv.R * PColor24Rec(Src).R + GrayConv.G * PColor24Rec(Src).G +
        GrayConv.B * PColor24Rec(Src).B);
      Inc(Src, SrcInfo.BytesPerPixel);
      Inc(Dst, DstInfo.BytesPerPixel);

One ugly workaround which just disregards the alpha channel is to increment Src by one before entering the loop in case we have 4 bytes per pixel, then the RGB values are not mixed up at least.

Greetings & bye