gpt4 book ai didi

delphi - 将 Base64 转换为位图

转载 作者:行者123 更新时间:2023-12-01 18:11:38 25 4
gpt4 key购买 nike

我尝试将 Base64 字符串转换为位图,但随后得到黑色图像。这是我用来解码的脚本:

function Base64ToBitmap(const S: string): TBitmap;
var
SS: TStringStream;
V: string;
begin
V := Decode(S);
SS := TStringStream.Create(V);
try
Result := TBitmap.Create;
Result.LoadFromStream(SS);
finally
SS.Free;
end;
end;

这是解码脚本:

function Decode(const Input: AnsiString): string;
var
bytes: TBytes;
utf8: UTF8String;
begin
bytes := EncdDecd.DecodeBase64(Input);
SetLength(utf8, Length(bytes));
Move(Pointer(bytes)^, Pointer(utf8)^, Length(bytes));
Result := string(utf8);
end;

位图转base64

function BitmapToBase64(ABitmap: TBitmap): string;
var
SS: TStringStream;
V: string;
begin
SS := TStringStream.Create('');
try
ABitmap.SaveToStream(SS);
V := SS.DataString;
Result := Encode(V);
finally
SS.Free;
end;
end;

编码:

function Encode(const Input: string): AnsiString;
var
utf8: UTF8String;
begin
utf8 := UTF8String(Input);
Result := EncdDecd.EncodeBase64(PAnsiChar(utf8), Length(utf8));
end;

为什么我会出现黑屏? Base64 字符串是屏幕截图。

最佳答案

您的代码不必要地复杂。这就是您所需要的:

{$APPTYPE CONSOLE}

uses
System.SysUtils,
System.Classes,
Vcl.Graphics,
Soap.EncdDecd;

function Base64FromBitmap(Bitmap: TBitmap): string;
var
Input: TBytesStream;
Output: TStringStream;
begin
Input := TBytesStream.Create;
try
Bitmap.SaveToStream(Input);
Input.Position := 0;
Output := TStringStream.Create('', TEncoding.ASCII);
try
Soap.EncdDecd.EncodeStream(Input, Output);
Result := Output.DataString;
finally
Output.Free;
end;
finally
Input.Free;
end;
end;

function BitmapFromBase64(const base64: string): TBitmap;
var
Input: TStringStream;
Output: TBytesStream;
begin
Input := TStringStream.Create(base64, TEncoding.ASCII);
try
Output := TBytesStream.Create;
try
Soap.EncdDecd.DecodeStream(Input, Output);
Output.Position := 0;
Result := TBitmap.Create;
try
Result.LoadFromStream(Output);
except
Result.Free;
raise;
end;
finally
Output.Free;
end;
finally
Input.Free;
end;
end;

var
Bitmap: TBitmap;
s: string;

begin
Bitmap := TBitmap.Create;
Bitmap.SetSize(100,100);
Bitmap.Canvas.Brush.Color := clRed;
Bitmap.Canvas.FillRect(Rect(20, 20, 80, 80));
s := Base64FromBitmap(Bitmap);
Bitmap.Free;
Bitmap := BitmapFromBase64(s);
Bitmap.SaveToFile('C:\desktop\temp.bmp');
end.

关于delphi - 将 Base64 转换为位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21909096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com