我需要有关Delphi位图和内存流的一些帮助。
我只是在摆弄Debenu PDF库,应该将pdf页面呈现为BMP,然后再将它们读回Image组件:

var
    Image1: TImage;
    Image2: TImage;
    PDF: TDebenuPDFLibrary;
    MS: TMemoryStream;

procedure TForm1.Button1Click(Sender: TObject);
    begin
        PDF.LoadFromFile('D:/something.pdf','');
        MS:=TMemoryStream.Create;
        PDF.RenderPageToStream(72,1,0,MS);
        MS.Position:= 0;
        Image1.Picture.Bitmap.LoadFromStream(MS);
        Image1.Repaint;
        MS.Free;
    end;


到目前为止,一切正常!
但是,当我尝试加载多个图像时,会收到运行时消息:

"Stream read error"


我正在尝试的代码:

var
    Image1: TImage;
    Image2: TImage;
    PDF: TDebenuPDFLibrary; //To render PDF to bitmaps
    MS: TMemoryStream;

procedure TForm1.Button1Click(Sender: TObject);
    begin
        PDF.LoadFromFile('D:/something.pdf','');
        MS:=TMemoryStream.Create;
        PDF.RenderPageToStream(72,1,0,MS); //First page
        PDF.RenderPageToStream(72,2,0,MS); //Second page
        MS.Position:= 0;
        Image1.Picture.Bitmap.LoadFromStream(MS);
        Image1.Repaint;
        Image2.Picture.Bitmap.LoadFromStream(MS);
        Image2.Repaint;
        MS.Free;
    end;


有什么帮助吗?

最佳答案

如果要从单个源流加载多个图像,则最好在流中定界图像,然后为每次加载使用单独的流。这使得在流数据中一个图像结束并下一幅图像开始的位置非常清晰。例如:

procedure RenderPDFToStream(PDF: TDebenuPDFLibrary; Page: Integer; Stream: TStream);
var
  MS: TMemoryStream;
  Size: Integer;
begin
  MS := TMemoryStream.Create;
  try
    PDF.RenderPageToStream(72, Page, 0, MS);
    Size := MS.Size;
    Stream.WriteBuffer(Size, SizeOf(Size));
    if Size > 0 then
      Stream.CopyFrom(MS, Size);
  finally
    MS.Free;
  end;
end;

procedure LoadBitmapFromStream(Stream: TStream; Bitmap: TBitmap);
var
  MS: TMemoryStream;
  Size: Integer;
begin
  MS := TMemoryStream.Create;
  try
    Stream.ReadBuffer(Size, SizeOf(Size));
    if Size > 0 then
      MS.CopyFrom(Stream, Size);
    MS.Position := 0;
    Bitmap.LoadFromStream(MS);
  finally
    MS.Free;
  end;
end;




var
  Image1: TImage;
  Image2: TImage;
  PDF: TDebenuPDFLibrary; //To render PDF to bitmaps

procedure TForm1.Button1Click(Sender: TObject);
var
  MS: TMemoryStream;
begin
  PDF.LoadFromFile('D:/something.pdf','');
  MS := TMemoryStream.Create;
  try
    RenderPDFToStream(PDF, 1, MS);
    RenderPDFToStream(PDF, 2, MS);
    MS.Position := 0;
    LoadBitmapFromStream(MS, Image1.Picture.Bitmap);
    LoadBitmapFromStream(MS, Image2.Picture.Bitmap);
  finally
    MS.Free;
  end;
end;

10-06 03:48