Because of a project, I had to save the pictures to the database and read them from the database when needed. At first, I thought it was very simple, not just a Stream. In fact, it is also very simple. Just look at it, there are a lot of codes, but , are all pitfalls!
Take a look at the source of TImage. There are loadfromStream and SavetoStream under Picture.Graphic. If you guessed correctly, you can just use these two functions. So, I made a demo test
There are two TImage in the demo. TImage1 puts a picture, and then uses the code to save the picture of TImage1 to Stream.TImage2 and then takes the picture from this Stream. It will naturally fall into place.
This is my code.
PicStream:=TMemoryStream.Create; Self.Image1.Picture.Graphic.SaveToStream(PicStream); PicStream.Position:=0; Self.Image2.Picture.Graphic.loadFromStream(PicStream); PicStream.Free;
But in fact, he made an error. So I searched Baidu again and again. The result was the same. (I don’t understand why there are so many problematic codes on the Internet. Is it because of different versions?)
So I tracked his TPicture.Assign because if I directly use TPicture.Assign to copy Timage1, there is no error.
procedure TPicture.Assign(Source: TPersistent);begin if Source = nil then SetGraphic(nil) else if Source is TPicture then SetGraphic(TPicture(Source).Graphic) else if Source is TGraphic then SetGraphic(TGraphic(Source)) else inherited Assign(Source);end;
It turns out that when he calls Assign, he will call SetGraphic to create a TGraphic object.
Therefore, if I still want to use the Graphic.loadFromStream function, I must manually create the TGraphic object myself. Otherwise, something will definitely go wrong. Moreover, the TGraphic must be created by calling different ClassTypes according to different image formats. The display is troublesome. A little more. And I used a TJPEGImage object, and calling its LoadFromStream can directly read the Stream, so I was lazy for a while.
Jpg:=TJPEGImage.Create; PicStream:=TMemoryStream.Create; Self.Image1.Picture.Graphic.SaveToStream(PicStream); PicStream.Position:=0; jpg.LoadFromStream(PicStream); Self.Image2.Picture.Assign(JPg ); PicStream.Free;
I don’t read many books. This blog is weird. Readers, I’ll just make do with it. I didn’t want to write this blog at first. But I saw that the code of the website cannot be used under D10. So I made a fool of myself. .