Jump to content
Lainkes

Save Timage picture as png

Recommended Posts

Hello,


I have a TImage that contains a picture.

Now I want to save this as a PNG file.

I found this code :

 

var PNG: TPNGImage; 

...
   
  // save image to file
  PNG := TPNGImage.Create;
  try
    PNG.Assign(imgPerson.Picture.Graphic); // ImgPerson is TImage component
    PNG.SaveToFile(image_path + file_name + '.PNG');
  finally
    PNG.Free;
  end;

When I open the png-file, I just see a grey square. 

Any idea what is going wrong?

 

Thanks

 

Lainkes

Share this post


Link to post

What graphic class is image? You can retrieve that from imgPerson.Picture.Graphic.Classname

Share this post


Link to post

Whether this works or not depends on the source image format. TPngImage does not support direct assignment from a TJpegImage, for example. In such a case you have to go through a TBitmap as intermediate.

procedure TForm1.Button1Click(Sender: TObject);
var
  png: TPngImage;
  bmp: TBitmap;
begin
  image1.Picture.LoadFromFile('C:\Users\Peter_2\Pictures\7.5. Stadtführung.jpg');
  bmp:= TBitmap.Create;
  try
    bmp.Assign(Image1.Picture.Graphic);
    png:= TPngImage.Create;
    try
      png.Assign(bmp);
      png.SaveToFile('C:\Users\Peter_2\Pictures\test.png');
      bmp.SaveToFile('C:\Users\Peter_2\Pictures\test.bmp');
    finally
      png.Free;
    end;
  finally
    bmp.Free;
  end;
  ShowMessage('Done');
end;

 

  • Like 1

Share this post


Link to post
5 hours ago, PeterBelow said:

Whether this works or not depends on the source image format. TPngImage does not support direct assignment from a TJpegImage, for example.

In which case, you should be getting an EConvertError exception raised, not a corrupted/empty file created.

Share this post


Link to post

Is there any chance the output file is locked (or not locked but the filesystem eventually fails to write to it)? I think I had seen OneDrive cause issues when trying to save too often onto the same filename (replace a file it was trying to sync to the cloud)

 

There is a free tool from SysInternals (now Microsoft) called ProcMon that may be helpful to see what is happening

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×