Store images in MS-Access Database using Delphi6

前端 未结 1 727
孤城傲影
孤城傲影 2021-01-07 07:29

How to Store images in the MS-Access Database using Blob data type? I want to use Record Type to store data. So, how to handle image in Record Type to save in database?

相关标签:
1条回答
  • 2021-01-07 08:21

    one possebility, which would allow storing diffent types of Images, you can shorten or expand the list in RegisterClasses.

    unit LoadSaveImageBlobs;
    
    // 20120224 by Thomas Wassermann
    
    interface
    uses Classes,DB,Graphics,Jpeg,PngImage;
    
    Procedure SavePicture2Blob(Blob: TBlobField; Picture: TPicture);
    Procedure LoadPictureFromBlob(Picture: TPicture; Blob: TBlobField);
    implementation
    
    Procedure SavePicture2Blob(Blob: TBlobField; Picture: TPicture);
    var
      ms, ms2: TMemoryStream;
      theClassName: AnsiString;
      len: Byte;
    begin
      ms := TMemoryStream.Create;
      try
        Blob.Clear;
        theClassName := Picture.Graphic.ClassName;
        len := Length(theClassName);
        ms.WriteBuffer(len, 1);
        if len > 0 then
          ms.WriteBuffer(theClassName[1], len);
        ms2 := TMemoryStream.Create;
        try
          Picture.Graphic.SaveToStream(ms2);
          ms2.Position := 0;
          if ms2.Size > 0 then
            ms.CopyFrom(ms2, ms2.Size);
        finally
          ms2.Free;
        end;
        Blob.LoadFromStream(ms);
      finally
        ms.Free;
      end;
    end;
    
    Procedure LoadPictureFromBlob(Picture: TPicture; Blob: TBlobField);
    var
      ms, ms2: TMemoryStream;
      len: Byte;
      theClassName: AnsiString;
      Graphic: TGraphic;
      GraphicClass: TGraphicClass;
    begin
      ms := TMemoryStream.Create;
      Blob.SaveToStream(ms);
      ms.Position := 0;
      try
        ms.ReadBuffer(len, 1);
        SetLength(theClassName, len);
        if len > 0 then
          ms.ReadBuffer(theClassName[1], len);
        GraphicClass := TGraphicClass(FindClass(theClassName));
        if (GraphicClass <> nil) and (len > 0) then
        begin
          Graphic := GraphicClass.Create;
          ms2 := TMemoryStream.Create;
          try
            ms2.CopyFrom(ms, ms.Size - len - 1);
            ms2.Position := 0;
            Graphic.LoadFromStream(ms2);
          finally
            ms2.Free;
          end;
          Picture.Assign(Graphic);
        end;
      finally
        ms.Free;
      end;
    end;
    
    
    initialization
    RegisterClasses([TIcon, TMetafile, TBitmap, TJPEGImage,TPngImage]);
    
    end.
    
    0 讨论(0)
提交回复
热议问题