user734781
user734781

Reputation: 273

How to convert bitmap images stored in a MySQL table to JPEG format?

I have a MySQL table that stores bitmap images and I want to convert them to JPEG format to the same table. Can anyone help me to find a solution ?

I need this to reduce the size of the table...

Upvotes: 0

Views: 1040

Answers (1)

TLama
TLama

Reputation: 76753

When you'd use ADO to access your MySQL database, it might look like this (it's untested). This code assumes you have the table you want to work with named as YourTable and the BLOB field you want to convert the images from as ImageField. Note you have to specify the connection string to your DB in the ConnectionString property of the ADOConnection object:

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;

Upvotes: 5

Related Questions