Saving images in various file formats

I have a routine procedure DrawStuff(ACanvas: TCanvas; const ARect: TRect) that draws something in the specified rectangle on TCanvas. DrawStuff now I'm DrawStuff with a PaintBox canvas. Now I am adding the Save as parameter, in which the user will be able to choose from a variety of file formats (bmp, wmf, jpg, ... - preferably as many TGraphic descendants as possible) to save the results of DrawStuff to.

Drawing on TMetafile and saving, which, like "bla.bmp" or Assign , is associated with TPicture , does not work correctly - for example. it creates files with the extension ".bmp" that are not bitmaps. Right now, I can’t imagine a solution that does not include a special case for each file format:

  • bmp - use TBitmap.Canvas .
  • wmf / emf: use TMetafileCanvas .
  • etc .. and others.

Do you know that I have any ideas?

+6
source share
1 answer

I think the β€œdumb” conversion would probably be so simple:

 type TGraphicTypeEnum = (gteBMP, gteJPG, gteTIF, gtePNG); procedure SaveGraphicAs(AGraphic : TGraphic; AGraphicType : TGraphicTypeEnum; AFileName : String); var vGraphicClass : TGraphicClass; vTargetGraphic : TGraphic; vBmp : TBitmap; begin case AGraphicType of gteBMP : vGraphicClass := TBitmap; gtejpg : vGraphicClass := TJPEGImage; gtetif : vGraphicClass := TWICImage; gtepng : vGraphicClass := TPngImage; else // EXIT; or raise... end; if aGraphic is vGraphicClass then //As suggested by Rob Kennedy AGraphic.SaveToFile(AFileName) else begin vBmp := nil; vTargetGraphic := vGraphicClass.Create; try vBmp := TBitmap.Create; vBmp.Assign(AGraphic); vTargetGraphic.Assign(vBmp); vTargetGraphic.SaveToFile(aFileName); finally vTargetGraphic.Free; vBmp.Free; end; end; end; 

Assigning TPicture did not work, because when assigning TPicture, TPicture converts the graphics to the class you are assigning.

Please note that in my example there are 2 conversion levels since the original image is converted to a bitmap before being converted to the final format. There can be quite a lot of information loss in the process. Most (all?) Of the graphic types know how to convert to and from TBitmap, but TJPEGImage has no idea how to convert to TPngImage and vice versa.

A more efficient conversion method may be developed that provides transparency and other effects specific to the file format, but this is known to me. But depending on your needs, this may be enough.

+9
source

Source: https://habr.com/ru/post/896815/


All Articles