Delphi – Convert BMP to PNG failed

I have the following simple code to convert a clipboard image to bmp and then to png:

if Clipboard.HasFormat (CF_PICTURE) then
begin
bitmap := TBitmap.Create;
png := TPNGImage.Create;
try
bitmap.Assign(Clipboard);
bitmap.SaveToFile(ExtractFilePath(application.ExeName) +' ilename.bmp');
png.Draw(bitmap.Canvas, Rect(0, 0, bitmap.Width, bitmap.Height));
png.SaveToFile(extractfilepath(application.ExeName) +' ilename.png');
finally
bitmap.free;
png.free;
end;
end;

Although the conversion to bmp works, I can even open it in mspaint and view its content, the conversion to png fails, and I have a blank png image. What am I doing wrong?

You have not set the size (height and width) of the PNG image object. You need to do this before drawing Do.

However, it is easier to do a simple task:

png.Assign(Bitmap);

div>

I have the following simple code to convert a clipboard image to bmp and then to png:

if Clipboard.HasFormat(CF_PICTURE ) then
begin
bitmap := TBitmap.Create;
png := TPNGImage.Create;
try
bitmap.Assign(Clipboard);
bitmap .SaveToFile(ExtractFilePath(application.ExeName) +' ilename.bmp');
png.Draw(bitmap.Canvas, Rect(0, 0, bitmap.Width, bitmap.Height));
png.SaveToFile(extractfilepath(application.ExeName) +' ilename.png');
finally
bitmap.free;
png.free;
end;
end;

Although the conversion to bmp works, I can even open it in mspaint and view its content, the conversion to png fails, and I have a blank png image. What am I doing wrong?

You have not set the size (height and width) of the PNG image object. You need to do this before drawing.

However, it is easier to do a simple task:

png.Assign(Bitmap);

Leave a Comment

Your email address will not be published.