Search code examples
arraysdelphibitmapdelphi-7

delphi convert byte of array to bitmap


How to convert byte of array into tbitmap using delphi 7, the array contain png header from memory.

bits[0]:= $9E;
bits[1]:= $20;
bits[2]:= $00;
bits[3]:= $00;
bits[4]:= $70;
bits[5]:= $AD;
bits[6]:= $BD;
bits[7]:= $1A;

I'm trying using tmemorystream to store the array into bitmap and using PNGImage from Gustav Daud to assign bitmap, but not luck.

uses .., PNGImage;

procedure TForm1.Button1Click(Sender: TObject);
var
  png      : TPNGObject;
  stream   : TMemoryStream;
  bits     : array[0..7] of byte;
begin
  bits[0]:= $9E;
  bits[1]:= $20;
  bits[2]:= $00;
  bits[3]:= $00;
  bits[4]:= $B8;
  bits[5]:= $EE;
  bits[6]:= $C4;
  bits[7]:= $1A;

  png:= TPNGObject.Create;
  try
    stream:= TMemoryStream.Create;
    try
      stream.Write(bits[0], sizeOf(bits));
      stream.Position:= 0;

      png.LoadFromStream(stream);
    finally
      stream.Free;
      JvImage1.Picture.Assign(png);
    end;
  finally
    png.Free;
  end;
end;

This give me stream error, is there any proper write about writing array byte to memorystream?

Thanks,


Solution

  • TJvImage.Picture is a standard TPicture, which means its Bitmap property is a standard TBitmap. You cannot load a PNG image into a TBitmap in VCL (you can in FireMonkey, which Delphi 7 does not support). You need to use a suitable third-party TGraphic-derived class for PNG images (Delphi 7 does not natively support PNGs, that was added in a later version), eg:

    uses
      ..., PngImage;
    
    var
      Png: TPngObject;
    try
      Png := TPngObject;
      try
        stream := TMemoryStream.create;
        try
          stream.Write(bits[0], sizeof(bits));
          stream.Position:= 0;
          Png.LoadFromStream(stream);
        finally
          stream.Free;
        end;
        JvImage1.Picture.Assign(Png);
      finally
        Png.free;
      end;
    end;
    

    Delphi 7, load PNG to TImage


    Update: However, that being said, the bytes you have shown are NOT a valid PNG graphic header to begin with. A PNG always starts with the following 8-byte signature:

    89 50 4E 47 0D 0A 1A 0A
    

    The bytes do not represent any PNG data chunk header, either (in case you are accidentally skipping past a PNG header).

    In fact, the bytes you have shown do not appear to represent any commonly-used graphic format. So you are likely misinterpreting the memory you are trying to examine.