views:

297

answers:

3

Hi dudes, 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;
+1  A: 

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.

Rob Kennedy
+1  A: 

You can use the following function to perform a search for the file and return the size.

function FindFileSize(Filename:string):integer;
var
  sr : TSearchRec;
begin
  if FindFirst(filename,faAnyFile-faDirectory,sr) = 0 then
    Result := sr.Size
  else
    raise EFileNotFoundException.Create(filename+' not found.');
  FindClose(sr);
end;
skamradt
A: 

blah, if I'm not mistaken, this is what you want

// this will return the size of the bitmap in bytes!
function BitmapSize(ABitmap: TBitmap): Cardinal;
var ms : TMemoryStream;
begin
     ms := TMemoryStream.Create;
     ABitmap.savetostream(ms);
     result := ms.size;
     FreeAndNil(ms);
end;

Have fun, don't forget to visit http://delphigeist.blogspot.com/ if the answer is helpful!

delphigeist
Isn't this Rob's solution, just less flexible (TBitmap instead of TGraphic) and less safe (no exception safety)?
Ulrich Gerhardt