解析 png 图片的十六进制字符流

时间:2021-07-19 16:35:37
uses pngimage;  

{从 png 图片到十六进制字符串}
function Png2Hex(png: TPngImage): string;
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
png.SaveToStream(stream);
SetLength(Result, stream.Size * 2);
BinToHex(stream.Memory, PChar(Result), stream.Size);
stream.Free;
end; {从十六进制字符串恢复 png 图片}
procedure Hex2Png(str: string; out png: TPngImage);
var
stream: TMemoryStream;
begin
if not Assigned(png) then png := TPngImage.Create;
stream := TMemoryStream.Create;
stream.SetSize(Length(str) div 2);
HexToBin(PChar(str), stream.Memory, stream.Size);
png.LoadFromStream(stream);
stream.Free;
end; {测试}
procedure TForm1.Button1Click(Sender: TObject);
var
png: TPngImage;
begin
png := TPngImage.Create;
png.LoadFromFile('c:/temp/test.png');
Memo1.Text := Png2Hex(png);
png.Free;
end; procedure TForm1.Button2Click(Sender: TObject);
var
png: TPngImage;
begin
png := TPngImage.Create;
Hex2Png(Memo1.Text, png);
Canvas.Draw(0, 0, png);
png.Free;
end;