用image1.Picture.Graphic.LoadFromStream(mStream);让image1显示一张图, 如果提前在image1的Picture属性中导入了一张JPG图, 那上面的代码就直接能用, 如果不导入就提示读内存错误了,//此时Graphic属性未创建 为nil 应该怎么才能让不管什么格式的图都直接能用代码直接显示出来啊? 就是IMGAE控件支持的图就行 先取流的前几字节判断图片类型,然后再赋予给 picture. TPicture只有loadfromfile,它需要根据扩展名 来决定图片格式。因此没办法从Stream加载,因此它不知道格式。你可以自己创建一个图片,然后赋给TPicture的Graphic属性。 或者,分析Stream的格式。我记得fastReport的TfrxPictureView.LoadPictureFromStream有这种代码,自己找一下。 用TWICImage,可以识别Stream里的图片格式。 unit bmpFromPicStream; interface uses Classes,Graphics, pngimage,jpeg, GifImg; function getBMPFromPicStream(Stm:TStream):TBitmap; implementation function getBMPFromPicStream(Stm:TStream):TBitmap; var buf: Array[0..9] of byte; bmp: TBITMAP; gif: TGIFImage; jpg: TJPEGImage; //png: TPNGobject; png: tpngimage; //stm: TMemoryStream; begin Result := nil; if Stm.Size < 10 then begin exit; end; try //支持的有bmp,gif,jpg,png stm.Position := 0; stm.ReadBuffer(buf[0],10); stm.Position := 0; bmp := TBITMAP.Create(); if (buf[0]=66) and (buf[1]=77) then begin //bmp bmp.LoadFromStream(stm) end else if (buf[0]=71) and (buf[1]=73) and (buf[2]=70) then begin //gif gif := TGifImage.Create(); gif.LoadFromStream(stm); bmp.Assign(gif); gif.Free() end else if (buf[1]=80) and (buf[2]=78) and (buf[3]=71) then begin //png png := tpngimage.create;//TPNGobject.Create(); png.LoadFromStream(stm); bmp.Assign(png); png.Free(); end else if (buf[6]=74) and (buf[7]=70) and (buf[8]=73) and (buf[9]=70) then begin //jpg jpg := TJpegImage.Create(); jpg.LoadFromStream(stm); bmp.Assign(jpg); jpg.Free(); end else begin //not image bmp.Free; bmp:=nil; end; finally end; result:=bmp; end; end. |
|