1

I have a simple TImage control on a form. I've assigned a Bitmap image at design-time. When running, I read the canvas using TImage.Picture.Bitmap.Canvas. Everything works fine. Then, I load a JPEG image in design-time. However, now when I read this canvas, suddenly the picture disappears.

Why does this happen and how can I avoid it?

procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  Canvas: TCanvas;
begin
  Canvas:= Image1.Picture.Bitmap.Canvas;
  //Do something with Canvas, but canvas is empty and image disappeared
end;
Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327

1 Answers1

12

This is expected, since a JPG image simply isn't a bitmap (BMP) image.

You have to convert it to a bitmap in order to do something with it:

var
  bm: TBitmap;
begin
  bm := TBitmap.Create;
  try
    bm.Assign(Image1.Picture.Graphic);
    bm.Canvas.DoSomethingReallyAwesome(ttExtraAwesome);
    bm.SaveToFile('C:\Users\Andreas Rejbrand\Desktop\test5.bmp');
  finally
    bm.Free;
  end;
Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
  • 1
    Hmm, I would have assumed (did assume) that loading it at design-time would have converted it to a bitmap, as a bitmap is the only door (which I know of) to access the image that's in the picture object. Yes I know how to convert formats as shown above, I just find it strange that the `TImage` or `TPicture` wouldn't have this covered. However I missed the `Graphic` reference you put. – Jerry Dodge Jan 26 '13 at 17:38
  • @JerryDodge: Since `TPicture` supports multiple image formats, via its `Graphic` property, there is no need for a design-time loaded image to be converted to a bitmap unnecessarily. – Remy Lebeau Jan 28 '13 at 07:23
  • Not only isn't there any need for such a conversion, it would also be bad. Say you include a 1920×1080 raster image of each planet in the solar system in your application. What would the file size of the EXE be if the images are (1) JPG, or (2) BMP? – Andreas Rejbrand Jan 28 '13 at 09:42