You need to determine which pixels are (fully) transparent.

Given the Delphi TPicture, in which there is some descendant of TGraphic, I need to understand the pixel color and opacity. I think I should have different implementations for each class, and I think I have TPngImage. Is there transparency support in 32-bit bitmaps? Can I solve the problem in a more general way than the following:

procedure GetPixelColorAndTransparency(const Picture: TPicture; X, Y: Integer; out Color: TColor; out Opacity: Byte); var Bmp: TBitmap; begin if Picture.Graphic is TPngImage then begin Opacity := (TPngImage(Picture.Graphic).AlphaScanline[Y]^)[X]; Color := TPngImage(Picture.Graphic).Pixels[ X, Y ]; end else if Picture.Graphic is TBitmap then begin Color := Picture.Bitmap.Canvas.Pixels[ X, Y ]; Opacity := 255; end else begin Bmp := TBitmap.Create; try Bmp.Assign(Picture.Graphic); Color := Bmp.Canvas.Pixels[ X, Y ]; Opacity := 255; finally Bmp.Free; end; end; end; 
+4
source share
2 answers

How about something like this:

 procedure GetPixelColorAndTransparency(const Picture: TPicture; X, Y: Integer; out Color: TColor; out Opacity: Byte); type PRGBQuadArray = ^TRGBQuadArray; TRGBQuadArray = array [Integer] of TRGBQuad; var Bmp: TBitmap; begin if Picture.Graphic is TPngImage then begin with TPngImage(Picture.Graphic) do begin Opacity := AlphaScanline[Y]^[X]; Color := Pixels[X, Y]; end; end else if Picture.Graphic is TBitmap then begin with Picture.Bitmap do begin Color := Canvas.Pixels[X, Y]; if PixelFormat = pf32Bit then begin Opacity := PRGBQuadArray(Scanline[Y])^[X].rgbReserved; end else if Color = TranparentColor then begin Opacity := 0; end else begin Opacity := 255; end; end; end else begin Bmp := TBitmap.Create; try Bmp.Assign(Picture.Graphic); Color := Bmp.Canvas.Pixels[X, Y]; if Color = Bmp.TranparentColor then begin Opacity := 0; end else begin Opacity := 255; end; finally Bmp.Free; end; end; end; 
+6
source

It is not optimized, but easy to understand:

 procedure GetPixelColorAndTransparency(const Picture: TPicture; X, Y: Integer; out Color: TColor; out Opacity: Byte); var Bmp: TBitmap; Color32: Cardinal; begin Bmp := TBitmap.Create; try Bmp.Assign(Picture.Graphic); Color32 := Bmp.Canvas.Pixels[ X, Y ]; Color := Color32 and $00FFFFFF; Opacity := Color32 shr 24; finally Bmp.Free; end; end; 
+2
source

Source: https://habr.com/ru/post/1399088/


All Articles