Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPEG Error #42 on assign

Tags:

delphi

Why can't I assign directly a MemoryStream to a Picture? Below I post two methods of assign a MemoryStream to a TImage. The Method1 doen't work and Method2 works. Why? Thanks Sam

Method1 : This method returns an JPEG error #42

Var
  ms1 : TMemoryStream;
  J : TJPEGImage;
  St : String;
begin
    ms1 := TMemoryStream.Create;
    try
      try
        St := 'somepath';
        IdFTP1.Get(St, ms1);
        if ms1.Size > 0 then
        Begin
          J := TJPEGImage.Create;
          try
            J.LoadFromStream(ms1);
            Image4.Picture := nil;
            Image4.Picture.Assign(J);  // here, I got an error #42 JPEG
          finally
            J.Free;
          end;
        End;
      except
        on e:exception do ShowMessage(e.message);
      end;
    finally
      ms1.Free;
    End;
  End;
end;

Method2 : This Method works

Var
  ms1, ms2 : TMemoryStream;
  J : TJPEGImage;
  St : String;
begin
    ms1 := TMemoryStream.Create;
    ms2 := TMemoryStream.Create;
    try
      try
        IdFTP1.Get(somepath, ms1);
        if ms1.Size > 0 then
        Begin
          J := TJPEGImage.Create;
          try
            J.LoadFromStream(ms1);
            ms1.SaveToFile('lixofoto.jpg');
            ms2.LoadFromFile('lixofoto.jpg');
            J.LoadFromStream(ms2);
            ImgProd.Picture.Assign(J);
            DeleteFile('lixofoto.jpg');
          finally
            J.Free;
          end;
        End;
      except

      end;
    finally
      ms1.Free;
      ms2.Free;
    End;
like image 343
SammyBF Avatar asked Dec 12 '22 10:12

SammyBF


1 Answers

You are not resetting the memory stream after the IdFTP.Get call. This means that the LoadFromStream call receives 0 bytes and hence the #42 error:

var
  ms1 : TMemoryStream;
  J : TJPEGImage;
  St : String;
begin
  try
    ms1 := TMemoryStream.Create;
    try
      St := 'somepath';
      IdFTP1.Get(St, ms1);
      if ms1.Size > 0 then
      begin
        ms1.Position := 0; // <-- add this
        J := TJPEGImage.Create;
        try
          J.LoadFromStream(ms1);
          Image4.Picture.Graphic := J;
        finally
          J.Free;
        end;
      end;
    finally
      ms1.Free;
    end;
  except
    on E: Exception do
      ShowMessage(E.Message);
  end;
end;
like image 99
whosrdaddy Avatar answered Dec 24 '22 02:12

whosrdaddy