【问题标题】:How to convert bitmap images stored in a MySQL table to JPEG format?如何将存储在 MySQL 表中的位图图像转换为 JPEG 格式?
【发布时间】:2012-11-29 19:11:46
【问题描述】:

我有一个存储位图图像的 MySQL 表,我想将它们转换为 JPEG 格式到同一个表。谁能帮我找到解决方案?

我需要这个来减小表格的大小...

【问题讨论】:

    标签: mysql delphi delphi-2010


    【解决方案1】:

    当您使用 ADO 访问您的 MySQL 数据库时,它可能看起来像这样(未经测试)。此代码假定您拥有要使用的名为 YourTable 的表和要转换图像的 BLOB 字段为 ImageField。请注意,您必须在 ADOConnection 对象的 ConnectionString 属性中指定与数据库的连接字符串:

    uses
      DB, ADODB, JPEG;
    
    procedure ConvertImage(BlobField: TBlobField);
    var
      BMPImage: TBitmap;
      JPEGImage: TJPEGImage;
      MemoryStream: TMemoryStream;
    begin
      MemoryStream := TMemoryStream.Create;
      try
        BlobField.SaveToStream(MemoryStream);
        BMPImage := TBitmap.Create;
        try
          MemoryStream.Position := 0;
          BMPImage.LoadFromStream(MemoryStream);
          JPEGImage := TJPEGImage.Create;
          try
            JPEGImage.Assign(BMPImage);
            MemoryStream.Position := 0;
            JPEGImage.SaveToStream(MemoryStream);
          finally
            JPEGImage.Free;
          end;
        finally
          BMPImage.Free;
        end;
        MemoryStream.Position := 0;
        BlobField.LoadFromStream(MemoryStream);
      finally
        MemoryStream.Free;
      end;
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    var
      ADOTable: TADOTable;
      ADOConnection: TADOConnection;
    begin
      ADOConnection := TADOConnection.Create(nil);
      try
        ADOConnection.LoginPrompt := False;
        // here you have to specify the connection string to your database
        // according to your connection parameters
        ADOConnection.ConnectionString := '<enter your connection string here>';
        ADOConnection.Open;
        if ADOConnection.Connected then
        begin
          ADOTable := TADOTable.Create(nil);
          try
            ADOTable.Connection := ADOConnection;
            ADOTable.TableName := 'YourTable';
            ADOTable.Filter := 'ImageField IS NOT NULL';
            ADOTable.Filtered := True;
            ADOTable.CursorType := ctOpenForwardOnly;
            ADOTable.Open;
            ADOTable.First;
            while not ADOTable.Eof do
            begin
              ADOTable.Edit;
              ConvertImage(TBlobField(ADOTable.FieldByName('ImageField')));
              ADOTable.Post;
              ADOTable.Next;
            end;
          finally
            ADOTable.Free;
          end;
        end;
      finally
        ADOConnection.Free;
      end;
    end;
    

    【讨论】:

    • 我认为需要在调用 JPEGImage.SaveToStream(MemoryStream) 之前重置 Stream 位置,不是吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2015-10-18
    相关资源
    最近更新 更多