如何获取TPNGImage的pixelformat或bitdepth

时间:2012-03-29 16:21:24

标签: delphi

使用Delphi 2010,您可以使用

获取jpg文件的pixelformat
TJPEGImage ( Image.Picture.Graphic ).PixelFormat  

有没有办法获得TPNGImage的pixelformat或bitdepth?

我尝试了这个,但它返回了错误的bitdepth:

 if Lowercase ( ExtractFileExt ( FPath ) ) = '.png' then
   StatusBar1.Panels [ 4 ].Text := ' Color Depth: ' + IntToStr( TPNGImage ( Image.Picture.Graphic ).Header.ColorType ) + '-bit';

2 个答案:

答案 0 :(得分:7)

您必须使用BitDepth字段

TPNGImage(Image.Picture.Graphic ).Header.BitDepth) 

并使用ColorType字段,你可以得到像这样的函数

function BitsForPixel(const AColorType,  ABitDepth: Byte): Integer;
begin
  case AColorType of
    COLOR_GRAYSCALEALPHA: Result := (ABitDepth * 2);
    COLOR_RGB:  Result := (ABitDepth * 3);
    COLOR_RGBALPHA: Result := (ABitDepth * 4);
    COLOR_GRAYSCALE, COLOR_PALETTE:  Result := ABitDepth;
  else
      Result := 0;
  end;
end;

并使用如此

procedure TForm72.Button1Click(Sender: TObject);
begin
    ShowMessage(IntToStr( BitsForPixel(
    TPNGImage ( Image1.Picture.Graphic ).Header.ColorType,
    TPNGImage ( Image1.Picture.Graphic ).Header.BitDepth
    )));
end;

答案 1 :(得分:6)

正如Rodrigo所指出的,Header.BitDepth是要使用的值。缺点是您必须根据ColorType解释它。您可以在PngImage.pas中的函数BytesForPixels中的注释中找到一些提示:

{Calculates number of bytes for the number of pixels using the}
{color mode in the paramenter}
function BytesForPixels(const Pixels: Integer; const ColorType,
  BitDepth: Byte): Integer;
begin
  case ColorType of
    {Palette and grayscale contains a single value, for palette}
    {an value of size 2^bitdepth pointing to the palette index}
    {and grayscale the value from 0 to 2^bitdepth with color intesity}
    COLOR_GRAYSCALE, COLOR_PALETTE:
      Result := (Pixels * BitDepth + 7) div 8;
    {RGB contains 3 values R, G, B with size 2^bitdepth each}
    COLOR_RGB:
      Result := (Pixels * BitDepth * 3) div 8;
    {Contains one value followed by alpha value booth size 2^bitdepth}
    COLOR_GRAYSCALEALPHA:
      Result := (Pixels * BitDepth * 2) div 8;
    {Contains four values size 2^bitdepth, Red, Green, Blue and alpha}
    COLOR_RGBALPHA:
      Result := (Pixels * BitDepth * 4) div 8;
    else
      Result := 0;
  end {case ColorType}
end;

如您所见,对于ARGB(= COLOR_RGBALPHA),每个颜色部分的BitDepth值分别加上alpha值。所以BitDepth = 8将导致每个像素的32位值。