Delphi – How to get the size of an image in bytes with Delphi

bytedelphiimagesize

my app has 3 controls: TThumbnailList (image viewer from TMS components), TImage, and TLabel. I wish that when I drag an image from TThumbnailList to TImage, and drop it, the TLabel object shows the size in bytes for that image. How do I get this?
Thanks in advance.

procedure TForm1.AssignImage;
begin
  //tl: TThumbnailList
  if (tl.ItemIndex>=0) then begin
    Image1.Picture.Assign(tl.Thumbnails.Items[tl.ItemIndex].Picture);
  end;
end;

procedure TForm1.Image1DragDrop(Sender, Source: TObject; X, Y: Integer);
begin
  if (Source is TThumbnailList) then AssignImage;
end;

procedure TForm1.Image1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState;
  var Accept: Boolean);
begin
  Accept:= Source is TThumbnailList;
end;

Best Answer

TImage does not have any way to determine the size of whatever graphic it happens to be holding at a given time. That's not its job. Its job is only to display things. The TGraphic object manages the in-memory representation, and it also determines how to draw itself onto a given canvas. TImage really knows nothing at all. TGraphic might, but it doesn't necessarily keep track of the file size; that might be different from the amount of memory necessary to have the data in memory.

The way to determine the size of a file is to have a file or something file-like, such as a stream. As you mentioned in your comment, you can save the image to a stream and then find out the size of the stream.

function GetGraphicSize(g: TGraphic): Integer;
var
  ms: TStream;
begin
  ms := TMemoryStream.Create;
  try
    g.SaveToStream(ms);
    Result := ms.Size;
  finally
    ms.Free;
  end;
end;

If that's too costly to compute each time you need the size, then remember the size from the first time you see the image so you don't need to computer it anew each time. How did the thumbnail list get its images to begin with? If they came from files, then you could have simply fetched the file size as you were generating the thumbnails.