delphipngvclbmp

How do I convert an image from PNG to BMP in Delphi VCL?


When I convert PNG picture to BMP picture via the routine below, then the colors are not the same in BMP as they are in the original PNG.

procedure TForm1.Button4Click(Sender: TObject);
var
  R: TRect;
  Bmp: TBitmap;
  Png: TPngImage;
begin
  Png := TPngImage.Create;
  try
    Png.LoadFromFile('C:\temp\Source.png');
    bmp := TBitmap.Create(Png.Width, Png.Height);
    try
      R := Rect(0, 0, Png.Width, Png.Height);
      bmp.Canvas.CopyRect(R, png.Canvas, R);
      bmp.SaveToFile('C:\temp\target.bmp')
    finally
      Bmp.Free;
    end;
  finally
    Png.Free;
  end;
end;

Could you provide me a hint on how to solve this issue, please?


Solution

  • I just tested the following procedure and it works without any issues. The colors look identical to my human eyes when comparing the original PNG and the result BMP:

    procedure ConvertPNGtoBMP(const PNGFileName, BMPFileName: string);
    begin
      var PNG := TPNGObject.Create;
      var BMP := TBitmap.Create;
      try
        PNG.LoadFromFile(PNGFileName); // Load the PNG image
        BMP.Assign(PNG); // Assign the PNG image to the BMP object
        BMP.SaveToFile(BMPFileName); // Save the BMP image
      finally
        PNG.Free;
        BMP.Free;
      end;
    end;
    

    Results:

    PNG to BMP Conversion results using the Delphi Programming Language

    I simply called it like this:

    ConvertPNGtoBMP('MyPhoto.png', 'MyPhoto.bmp');