4

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;
4

1 回答 1

13

您没有在IdFTP.Get通话后重置内存流。这意味着LoadFromStream调用接收到 0 个字节,因此会出现 #42 错误:

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;
于 2013-10-15T18:36:13.773 回答