加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – TBitmap32.LoadFromStream()自动识别图像格式

发布时间:2020-12-15 09:20:43 所属栏目:大数据 来源:网络整理
导读:我正在使用Delphi XE2(Update 3)和GR32.我无法使用TBitmap32.LoadFromStream()来加载图像数据.它引发了以下异常: Project MyApp.exe raised exception class EInvalidGraphic with message 'Bitmap image is not valid'. 码 uses GR32,GifImg,PngImage,Vcl.
我正在使用Delphi XE2(Update 3)和GR32.我无法使用TBitmap32.LoadFromStream()来加载图像数据.它引发了以下异常:

Project MyApp.exe raised exception class EInvalidGraphic with message 'Bitmap image is not valid'.

uses GR32,GifImg,PngImage,Vcl.Graphics;

var
  pic: TBitmap32;
  bs: TBytesStream;
begin
  bs := TBytesStream.Create(TClientDataSet(cds).FieldByName('filedata').AsBytes);
  try
    pic := TBitmap32.Create;
    try
//      bs.SaveToFile('c:delme.png');
//      pic.LoadFromFile('c:delme.png');
      pic.LoadFromStream(bs); // <- EInvalidGraphic exception
      // do something with 'pic'
    finally
      FreeAndNil(pic);
    end;
  finally
    FreeAndNil(bs);
  end;
end;

解决方法(S)

如果我注释LoadFromStream()代码并取消注释前两行,它就可以工作 – 因此它可以在从文件加载时确定图像格式.在此示例中,bs包含有效的PNG图像.但是,有时它可能是GIF,JPG,BMP或其他图形格式.

我也知道我可以使用中间对象(例如,TPNGImage,TJPEGImage等),使用LoadFromStream()将图像数据加载到中间对象中,然后将其()分配给TBitmap32.但是,如果没有中间对象,TBitmap32可以处理任何类型的图像会更好,我认为它可以…

有没有人知道如何使用TBitmap32.LoadFromStream()加载图像并让它自动识别图像格式而不将图像保存到HDD(即使是暂时的),或使用中间对象?

解决方法

这是LoadFromFile的代码:

procedure TCustomBitmap32.LoadFromFile(const FileName: string);
var
  FileStream: TFileStream;
  Header: TBmpHeader;
  P: TPicture;
begin
  FileStream := TFileStream.Create(Filename,fmOpenRead);
  try
    FileStream.ReadBuffer(Header,SizeOf(TBmpHeader));

    // Check for Windows bitmap magic bytes...
    if Header.bfType = $4D42 then
    begin
      // if it is,use our stream read method...
      FileStream.Seek(-SizeOf(TBmpHeader),soFromCurrent);
      LoadFromStream(FileStream);
      Exit;
    end
  finally
    FileStream.Free;
  end;

  // if we got here,use the fallback approach via TPicture...
  P := TPicture.Create;
  try
    P.LoadFromFile(FileName);
    Assign(P);
  finally
    P.Free;
  end;
end;

如您所见,代码检查文件是否是Windows位图.如果是,则通过调用LoadFromStream直接加载它.

如果没有,则将其加载到TPicture中,然后分配给该实例.

关键是LoadFromStream只能理解Windows位图.它不了解任何其他文件格式.而你正在尝试加载PNG.因此,如果不使用中间对象,就无法做到所需.

您的解决方案是:

>实例化TPNGImage对象.>在该实例上调用LoadFromStream.>在传递TPNGImage实例的TBitmap32实例上调用Assign.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读