分配时出现JPEG错误#42

时间:2013-10-15 17:40:31

标签: delphi

为什么我不能直接将MemoryStream分配给图片? 下面我发布了两种将MemoryStream分配给TImage的方法。方法1不起作用,方法2起作用。为什么? 谢谢 萨姆

方法1:此方法返回JPEG错误#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;

方法2:此方法有效

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;

1 个答案:

答案 0 :(得分:11)

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;