Сохранение и извлечение JPEG изображений (и не только)
Сохранение и извлечение JPEG изображений (и не только)
Сохранение и извлечение JPEG изображений (и не только) Поля типа Graphic предназначены для работы с типами данных Bitmap, Icon, Metafiles, как и компонент DBImage. Чтобы сохранить JPEG изображение, поле Blob должно иметь подтип Graphic, тогда мы сможем использовать приведенный код. uses jpeg; procedure TForm1.Button1Click(Sender: TObject); var Jpg: TJpegImage; Stream: TMemoryStream; begin Jpg := nil; Stream := nil; try // Создажим JPEG image и загрузим в него изображение из файла Jpg := TJpegImage.Create; Jpg.LoadFromFile('test.jpg'); // Создадим поток и загрузим изображение в поток Stream := TMemoryStream.Create; Jpg.SaveToStream(Stream); Stream.Position := 0; Table1.Append; // Получим данные из потока в наше поле Blob field TBlobField(Table1.FieldByName('Graph')).LoadFromStream(Stream); Table1.Post; except jpg.Free; Stream.Free; raise; end; jpg.Free; Stream.Free; end; To display a JPEG image stored in a Blob field in a TImage control, we can use a code like the following for example in an AfterScroll event: procedure TForm1.Table1AfterScroll(DataSet: TDataSet); var Stream: TMemoryStream; Jpg: TJpegImage; begin Jpg := nil; Stream := nil; try // Create a stream and load the contents of the Blob field Stream := TMemoryStream.Create; TBlobField(Table1.FieldByName('Graph')).SaveToStream(Stream); if Stream.Size > 0 then begin // Create a JPEG image and load it from the stream Jpg := TJpegImage.Create; Stream.Position := 0; Jpg.LoadFromStream(Stream); // Assign the JEPG image to the Picture property of an Image Image1.Picture.Assign(Jpg); end else Image1.Picture.Assign(nil); except Image1.Picture.Assign(nil); end; jpg.Free; Stream.Free; end; If you want to be able to store different images types (bitmaps, icons, metafiles and jpegs) in a field, we can add a byte at the beginning of the stream to indicate the image kind, and then we have to read this byte first to know how to load and display the image appropriately. We designed a full example to show how to do it. 1) Place the following components on a form and set their properties: Table1: TTable TableName = 'GraphTest.DB' FieldDefs = Field1 Name = 'Graph' DataType = ftBlob Size = 1 StoreDefs = True DataSource1: TDataSource DataSet = Table1 DBNavigator1: TDBNavigator DataSource = DataSource1 Align = alBottom PopupMenu1: TPopupMenu Items = mnuLoad: TMenuItem Caption = '&Load...' mnuClear: TMenuItem Caption = '&Clear' Image1: TImage PopupMenu = PopupMenu1 dlgOpenPicture: TOpenPictureDialog Options = [ofReadOnly, ofHideReadOnly, ofPathMustExist, ofFileMustExist, ofNoTestFileCreate, ofEnableSizing] 2) Add "jpeg" to the uses clause: uses ..., jpeg; 3) Add the following type declaration to the unit: type TGraphType = (gtBitmap, gtIcon, gtMetafile, gtJpeg); 4) Generate the following events: procedure TForm1.FormCreate(Sender: TObject); begin if Not FileExists('GraphTest.DB') then Table1.CreateTable; Table1.Open; end; procedure TForm1.mnuLoadClick(Sender: TObject); var Jpg: TJpegImage; Stream: TMemoryStream; FileExt: string; GraphType: TGraphType; begin if dlgOpenPicture.Execute then begin Jpg := nil; Stream := nil; try Stream := TMemoryStream.Create; FileExt := LowerCase(ExtractFileExt(dlgOpenPicture.FileName)); if (FileExt = '.bmp') or (FileExt = '.dib') then begin GraphType := gtBitmap; Stream.Write(GraphType, 1); with Image1.Picture.Bitmap do begin LoadFromFile(dlgOpenPicture.FileName); Image1.Picture.Bitmap.SaveToStream(Stream); end; end else if (FileExt = '.ico') then begin GraphType := gtIcon; Stream.Write(GraphType, 1); with Image1.Picture.Icon do begin LoadFromFile(dlgOpenPicture.FileName); Image1.Picture.Bitmap.SaveToStream(Stream); end; end else if (FileExt = '.emf') or (FileExt = '.wmf') then begin GraphType := gtMetafile; Stream.Write(GraphType, 1); with Image1.Picture.Metafile do begin LoadFromFile(dlgOpenPicture.FileName); Image1.Picture.Bitmap.SaveToStream(Stream); end; end else if (FileExt = '.jpg') or (FileExt = '.jpeg') or (FileExt = '.jpe') then begin Jpg := TJpegImage.Create; Jpg.LoadFromFile(dlgOpenPicture.FileName); Image1.Picture.Assign(Jpg); GraphType := gtJpeg; Stream.Write(GraphType, 1); Jpg.SaveToStream(Stream); end; if (Table1.State <> dsEdit) and (Table1.State <> dsInsert) then Table1.Edit; Stream.Position := 0; TBlobField(Table1.FieldByName('Graph')).LoadFromStream(Stream); except jpg.Free; Stream.Free; raise; end; jpg.Free; Stream.Free; end; end; procedure TForm1.mnuClearClick(Sender: TObject); begin Image1.Picture.Assign(nil); if (Table1.State <> dsEdit) and (Table1.State <> dsInsert) then Table1.Edit; Table1.FieldByName('Graph').Assign(nil); // Clear the field end; procedure TForm1.Table1AfterScroll(DataSet: TDataSet); var Stream: TMemoryStream; Jpg: TJpegImage; GraphType: TGraphType; begin Jpg := nil; Stream := nil; try Stream := TMemoryStream.Create; TBlobField(Table1.FieldByName('Graph')).SaveToStream(Stream); if Stream.Size > 0 then begin Stream.Position := 0; Stream.Read(GraphType, 1); case GraphType of gtBitmap: Image1.Picture.Bitmap.LoadFromStream(Stream); gtIcon: Image1.Picture.Icon.LoadFromStream(Stream); gtMetafile: Image1.Picture.Metafile.LoadFromStream(Stream); gtJpeg: begin Jpg := TJpegImage.Create; Jpg.LoadFromStream(Stream); Image1.Picture.Assign(Jpg); end else Image1.Picture.Assign(nil); // Clear the image end; end else Image1.Picture.Assign(nil); except Image1.Picture.Assign(nil); end; jpg.Free; Stream.Free; end;