Search code examples
mysqlimagedelphiblobvcl

Image conversion from TImage to Blob causes image corruption


I'm currently having an issue where I take an image that is displayed in a TImage component, convert it and storing it in a BLOB field. Now I know that this is not an optimized solution, but for my purposes this is fine. Not going to store huge amounts of images.

The image gets saved into a Blob field of a MySQL database. The problem comes when I want to display the image again in a TImage component, it only shows like half of the image, the bottem part gets corrupted in some way.

Here is the code for the insert into the DB:

image1.Picture.LoadFromFile(fileName);
if image1.Picture.Graphic <> nil then
begin
  Field := TBlobField(database.qDBImages.FieldByName('image_one'));
  stream_one := database.qDBImages.CreateBlobStream(Field, bmWrite);
  try
    image1.Picture.Graphic.SaveToStream(stream_one);
    ShowMessage('we are saving to stream');
  finally
    database.qDBImages.Post;
    stream.Free;
  end;

Now the issue comes when I have to display the value back into a TImage, then it gets corrupted. Here is the code to display the image:

var
  Field : TBlobField;
  Stream : TStream;
  Jpg : TJPEGImage;
begin
  database.qDBImages.Active := true;

  if database.qDBImages.Active then
  begin
    Field := TBlobField(database.qDBImages.FieldByName('image_one'));
    Stream := database.qDBImages.CreateBlobStream(Field, bmRead);
    Jpg := TJPEGImage.Create;
    try
      Jpg.LoadFromStream(Stream);
      Image1.Picture.Graphic := Jpg;
    finally
      Jpg.Free;
      Stream.Free;
    end;
  end;

Is there any other way to convert the image to the blob field, and not get corrupted when retrieved?

I did read somewhere that it might have to to do with the length of the blob, but I'm not sure.

Is there any way to improve this?


Solution

  • So the solution was taken from the suggestion from Oliver on top. I just changed the blob field to a mediumblob field increasing the max size from 64KB to 16MB. So all thanks to Olivier