Base64
From Lazarus wiki
Revision as of 16:41, 14 August 2023 by Alextpp (talk | contribs) (→Convert Base64 string to picture, 2)
Various code examples to handle Base64 encoded strings.
Convert Base64 string to picture, 1
Example from forum member wp.
procedure DecodeBase64ToStream(AStream: TStream; const s: string; strict:boolean=false);
var
SD : String;
Instream: TStringStream;
Decoder: TBase64DecodingStream;
begin
if Length(s)=0 then
Exit;
SD := S;
while Length(Sd) mod 4 > 0 do
SD := SD + '=';
Instream:=TStringStream.Create(SD);
try
if strict then
Decoder:=TBase64DecodingStream.Create(Instream,bdmStrict)
else
Decoder:=TBase64DecodingStream.Create(Instream,bdmMIME);
try
AStream.CopyFrom(Decoder, Decoder.Size);
AStream.Position := 0;
finally
Decoder.Free;
end;
finally
Instream.Free;
end;
end;
var
base64String: String =
'iVBORw0KGgoAAAANSUhEUgAAARIAAAAdCAYAAABmFuNCAAAFPElEQVR4Xu2cy5oiIQyFdaPP'+
'PCt1Nc9sbxyRTlcqJuFAYdvf9HGjllSAQ/grXGR/vV5vO76oABWgAhsU2BMkG9TjrVSACjwU'+
'IEjoCFSACmxWwAXJ4XDY7fe73fX6scpg1nVtNLLZWzPEzqzyM6/3+sasdkT8kHlVlVo+/wSS'+
'4/Hv7nY71XBlf7nD5M/j86zruvEimzW/Q8oSDbnMjhiZVX7m9V7fmNWOiB8yr7zvaw3diKQI'+
'WF4CEd0ZZ1y3jahtaoDcgmngEi3JS4ASlTnL6zvrxbyqU7Z0QNLM8k/mtb2Pi4bT50hKCHSP'+
'ZR72Pz6uaVRhfxSIWIDs7+Q4n8+706k+Db8K/wkUOwTrypSJqQAV2KzAVJBoiPSCpEAkikCK'+
'rQKTm5NAohPCZLMv0AAVGFZgGkgsROpkLRaRaIhE0Yet4eVyeUQpAhdvcnhYFd5IBahAlwJT'+
'QLIFIqW0Nhqx0YdEHTog8dIwKulqeyamAtMU2AySGRAptfGGNRUgF1PZU5L2eVlymlI0RAWo'+
'QKgADJIKjDKBWveWWICUaz3DGSmRXmLTpf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7BFuembaA4qUxUKk'+
'dRRcBeL7j5CcVQbdJrNsUkMeIdnrS1/90Vv+7TXWm14yz49azDfDrZf7/OMhdWebdWwej1rk'+
'UYu9vvQb/PCtZ7YWgZEjEpGICLEz64g+5rX9iD5q+H9p+PYzWxFIMA0VoAI/W4G3z5H8bHlY'+
'OipABRAFCBJEJaahAlQgVYAgoYNQASqwWYF/o2XhCcA1FYIAAAAASUVORK5CYII=';
procedure TForm1.Button1Click(Sender: TObject);
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
DecodeBase64ToStream(stream, base64String);
Image1.Picture.LoadFromStream(stream);
finally
stream.Free;
end;
end;
Convert Base64 string to picture, 2
This procedure is from forum member KodeZwerg.
procedure DisplayBase64(const ABase64String: AnsiString; const AImage: TImage);
He created a pretty easy to handle method that supports now all (?) formats that Lazarus Graphics offers. To name them: JPEG, PNG, GIF, BMP, ICO and TIFF. Full unit:
unit uMain;
{$mode objfpc}{$H+}
interface
uses
Classes , SysUtils , Forms , Controls , Graphics , Dialogs , ExtCtrls ,
StdCtrls,
Base64{, fpimage, fpreadpng};
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Image1: TImage;
OpenDialog1: TOpenDialog;
procedure Button1Click(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ Load a file into its corresponding image class }
function LoadJPGImage(const AFilename: string): TJPEGImage;
begin
Result := TJPEGImage.Create;
try
Result.LoadFromFile(AFilename);
finally
end;
end;
function LoadPNGImage(const AFilename: string): TPortableNetworkGraphic;
begin
Result := TPortableNetworkGraphic.Create;
try
Result.LoadFromFile(AFilename);
finally
end;
end;
function LoadGIFImage(const AFilename: string): TGIFImage;
begin
Result := TGIFImage.Create;
try
Result.LoadFromFile(AFilename);
finally
end;
end;
function LoadBMPImage(const AFilename: string): TBitmap;
begin
Result := TBitmap.Create;
try
Result.LoadFromFile(AFilename);
finally
end;
end;
function LoadICOImage(const AFilename: string): TIcon;
begin
Result := TIcon.Create;
try
Result.LoadFromFile(AFilename);
finally
end;
end;
function LoadTIFFImage(const AFilename: string): TTiffImage;
begin
Result := TTiffImage.Create;
try
Result.LoadFromFile(AFilename);
finally
end;
end;
{ convert image to base64 }
function JPGToBase64(const AImage: TJPEGImage): AnsiString;
var
stream: TMemoryStream;
encodingStream: TBase64EncodingStream;
output: TStringStream;
begin
stream := TMemoryStream.Create;
try
AImage.SaveToStream(stream);
stream.Position := 0;
output := TStringStream.Create;
try
encodingStream := TBase64EncodingStream.Create(output);
try
encodingStream.CopyFrom(stream, stream.Size);
encodingStream.Flush;
Result := output.DataString;
finally
encodingStream.Free;
end;
finally
output.Free;
end;
finally
stream.Free;
end;
end;
function PNGToBase64(const AImage: TPortableNetworkGraphic): AnsiString;
var
stream: TMemoryStream;
encodingStream: TBase64EncodingStream;
output: TStringStream;
begin
stream := TMemoryStream.Create;
try
AImage.SaveToStream(stream);
stream.Position := 0;
output := TStringStream.Create;
try
encodingStream := TBase64EncodingStream.Create(output);
try
encodingStream.CopyFrom(stream, stream.Size);
encodingStream.Flush;
Result := output.DataString;
finally
encodingStream.Free;
end;
finally
output.Free;
end;
finally
stream.Free;
end;
end;
function GIFToBase64(const AImage: TGIFImage): AnsiString;
var
stream: TMemoryStream;
encodingStream: TBase64EncodingStream;
output: TStringStream;
begin
stream := TMemoryStream.Create;
try
AImage.SaveToStream(stream);
stream.Position := 0;
output := TStringStream.Create;
try
encodingStream := TBase64EncodingStream.Create(output);
try
encodingStream.CopyFrom(stream, stream.Size);
encodingStream.Flush;
Result := output.DataString;
finally
encodingStream.Free;
end;
finally
output.Free;
end;
finally
stream.Free;
end;
end;
function BMPToBase64(const AImage: TBitmap): AnsiString;
var
stream: TMemoryStream;
encodingStream: TBase64EncodingStream;
output: TStringStream;
begin
stream := TMemoryStream.Create;
try
AImage.SaveToStream(stream);
stream.Position := 0;
output := TStringStream.Create;
try
encodingStream := TBase64EncodingStream.Create(output);
try
encodingStream.CopyFrom(stream, stream.Size);
encodingStream.Flush;
Result := output.DataString;
finally
encodingStream.Free;
end;
finally
output.Free;
end;
finally
stream.Free;
end;
end;
function ICOToBase64(const AImage: TIcon): AnsiString;
var
stream: TMemoryStream;
encodingStream: TBase64EncodingStream;
output: TStringStream;
begin
stream := TMemoryStream.Create;
try
AImage.SaveToStream(stream);
stream.Position := 0;
output := TStringStream.Create;
try
encodingStream := TBase64EncodingStream.Create(output);
try
encodingStream.CopyFrom(stream, stream.Size);
encodingStream.Flush;
Result := output.DataString;
finally
encodingStream.Free;
end;
finally
output.Free;
end;
finally
stream.Free;
end;
end;
function TIFFToBase64(const AImage: TTiffImage): AnsiString;
var
stream: TMemoryStream;
encodingStream: TBase64EncodingStream;
output: TStringStream;
begin
stream := TMemoryStream.Create;
try
AImage.SaveToStream(stream);
stream.Position := 0;
output := TStringStream.Create;
try
encodingStream := TBase64EncodingStream.Create(output);
try
encodingStream.CopyFrom(stream, stream.Size);
encodingStream.Flush;
Result := output.DataString;
finally
encodingStream.Free;
end;
finally
output.Free;
end;
finally
stream.Free;
end;
end;
{ convert base64 to bytes }
function Base64ToBytes(const ABase64String: AnsiString): TBytes;
var
decodedStream: TBase64DecodingStream;
begin
decodedStream := TBase64DecodingStream.Create(TStringStream.Create(ABase64String));
try
SetLength(Result, decodedStream.Size);
decodedStream.ReadBuffer(Result[0], decodedStream.Size);
finally
decodedStream.Free;
end;
end;
{ determine the image format }
function GetBytesFormat(const AData: TBytes): Integer;
var
signature: TBytes;
begin
Result := -1;
signature := Copy(AData, 0, 8);
if CompareMem(@signature[0], @[$FF, $D8, $FF, $DB], 4) then
Result := 0 // JPEG
else
if CompareMem(@signature[0], @[$FF, $D8, $FF, $E0, $00, $10, $4A, $46], 8) then
Result := 0 // JPEG
else
if CompareMem(@signature[0], @[$49, $46, $00, $01], 4) then
Result := 0 // JPEG
else
if CompareMem(@signature[0], @[$FF, $D8, $FF, $EE], 4) then
Result := 0 // JPEG
else
if CompareMem(@signature[0], @[$FF, $D8, $FF, $E1], 4) and CompareMem(@signature[6], @[$45, $78], 2) then
Result := 0 // JPEG
else
if CompareMem(@signature[0], @[$69, $66, $00, $00], 4) then
Result := 0 // JPEG
else
if CompareMem(@signature[0], @[$FF, $D8, $FF, $E0], 4) then
Result := 0 // JPEG
else
if CompareMem(@signature[0], @[$89, $50, $4E, $47, $0D, $0A, $1A, $0A], 8) then
Result := 1 // PNG
else
if CompareMem(@signature[0], @[$47, $49, $46, $38, $37, $61], 6) then
Result := 2 // GIF87a
else
if CompareMem(@signature[0], @[$47, $49, $46, $38, $39, $61], 6) then
Result := 2 // GIF89a
else
if CompareMem(@signature[0], @[$42, $4D], 2) then
Result := 3 // BMP
else
if CompareMem(@signature[0], @[$00, $00, $01, $00], 4) then
Result := 4 // ICO
else
if CompareMem(@signature[0], @[$49, $49, $2A, $00], 4) then
Result := 5 // TIF
else
if CompareMem(@signature[0], @[$4D, $4D, $00, $2A], 4) then
Result := 5 // TIFF
;
end;
{ convert the bytes into the corresponding image class }
function Base64ToJPG(const AData: TBytes): TJPEGImage;
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
stream.WriteBuffer(AData[0], Length(AData));
stream.Position := 0;
Result := TJPEGImage.Create;
try
Result.LoadFromStream(stream);
finally
end;
finally
stream.Free;
end;
end;
function Base64ToPNG(const AData: TBytes): TPortableNetworkGraphic;
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
stream.WriteBuffer(AData[0], Length(AData));
stream.Position := 0;
Result := TPortableNetworkGraphic.Create;
try
Result.LoadFromStream(stream);
finally
end;
finally
stream.Free;
end;
end;
function Base64ToGIF(const AData: TBytes): TGIFImage;
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
stream.WriteBuffer(AData[0], Length(AData));
stream.Position := 0;
Result := TGIFImage.Create;
try
Result.LoadFromStream(stream);
finally
end;
finally
stream.Free;
end;
end;
function Base64ToBMP(const AData: TBytes): TBitmap;
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
stream.WriteBuffer(AData[0], Length(AData));
stream.Position := 0;
Result := TBitmap.Create;
try
Result.LoadFromStream(stream);
finally
end;
finally
stream.Free;
end;
end;
function Base64ToICO(const AData: TBytes): TIcon;
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
stream.WriteBuffer(AData[0], Length(AData));
stream.Position := 0;
Result := TIcon.Create;
try
Result.LoadFromStream(stream);
finally
end;
finally
stream.Free;
end;
end;
function Base64ToTIFF(const AData: TBytes): TTiffImage;
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
stream.WriteBuffer(AData[0], Length(AData));
stream.Position := 0;
Result := TTiffImage.Create;
try
Result.LoadFromStream(stream);
finally
end;
finally
stream.Free;
end;
end;
{ analyze and display a found image format into a TImage }
procedure DisplayBase64(const ABase64String: AnsiString; const AImage: TImage);
var
bytes: TBytes;
jpg: TJPEGImage;
png: TPortableNetworkGraphic;
gif: TGIFImage;
bmp: TBitmap;
ico: TIcon;
tif: TTiffImage;
begin
bytes := Base64ToBytes(ABase64String);
AImage.Picture.Clear;
case GetBytesFormat(bytes) of
0: begin jpg := Base64ToJPG(bytes); AImage.Picture.Assign(jpg); jpg.Free; end;
1: begin png := Base64ToPNG(bytes); AImage.Picture.Assign(png); png.Free; end;
2: begin gif := Base64ToGIF(bytes); AImage.Picture.Assign(gif); gif.Free; end;
3: begin bmp := Base64ToBMP(bytes); AImage.Picture.Assign(bmp); bmp.Free; end;
4: begin ico := Base64ToICO(bytes); AImage.Picture.Assign(ico); ico.Free; end;
5: begin tif := Base64ToTIFF(bytes); AImage.Picture.Assign(tif); tif.Free; end;
end;
end;
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
{ all supported formats }
jpg: TJPEGImage;
png: TPortableNetworkGraphic;
gif: TGIFImage;
bmp: TBitmap;
ico: TIcon;
tif: TTiffImage;
{ the base64 encoded data }
base64String: AnsiString;
ext: string;
begin
base64String := '';
if OpenDialog1.Execute then
begin
ext := LowerCase(ExtractFileExt(OpenDialog1.FileName));
if ext = '.jpg' then
begin
jpg := LoadJPGImage(OpenDialog1.FileName);
base64String := JPGToBase64(jpg);
jpg.Free;
end
else
if ext = '.jpeg' then
begin
jpg := LoadJPGImage(OpenDialog1.FileName);
base64String := JPGToBase64(jpg);
jpg.Free;
end
else
if ext = '.jfif' then
begin
jpg := LoadJPGImage(OpenDialog1.FileName);
base64String := JPGToBase64(jpg);
jpg.Free;
end
else
if ext = '.png' then
begin
png := LoadPNGImage(OpenDialog1.FileName);
base64String := PNGToBase64(png);
png.Free;
end
else
if ext = '.gif' then
begin
gif := LoadGIFImage(OpenDialog1.FileName);
base64String := GIFToBase64(gif);
gif.Free;
end
else
if ext = '.bmp' then
begin
bmp := LoadBMPImage(OpenDialog1.FileName);
base64String := BMPToBase64(bmp);
bmp.Free;
end
else
if ext = '.ico' then
begin
ico := LoadICOImage(OpenDialog1.FileName);
base64String := ICOToBase64(ico);
ico.Free;
end
else
if ext = '.tif' then
begin
tif := LoadTIFFImage(OpenDialog1.FileName);
base64String := TIFFToBase64(tif);
tif.Free;
end
else
if ext = '.tiff' then
begin
tif := LoadTIFFImage(OpenDialog1.FileName);
base64String := TIFFToBase64(tif);
tif.Free;
end;
if base64String <> '' then
DisplayBase64(base64String, Image1);
end;
end;
end.
Convert Base64 string to picture, using BGRABitmap
This unit is from forum member KodeZwerg. You must install the BGRABitmap component.
unit ubase64image;
{$mode ObjFPC}{$H+}
interface
uses
Classes, SysUtils, Graphics, ExtCtrls,
Base64,
BGRABitmap, BGRABitmapTypes, BGRAGraphics, BGRASVG, BGRAOpenRaster, BGRAPhoxo, BGRAPaintNet;
function FileToStream(const AFilename: string): TStream;
function StreamToBase64(const AStream: TStream): AnsiString;
function Base64ToStream(const ABase64String: AnsiString): TStream;
procedure AssignBase64ToImage(const ABase64String: AnsiString; const AImage: TImage; const AFastMode: Boolean = False);
implementation
function FileToStream(const AFilename: string): TStream;
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
Result := TMemoryStream.Create;
try
Result.CopyFrom(FileStream, FileStream.Size);
finally
Result.Position := 0;
end;
finally
FileStream.Free;
end;
end;
function StreamToBase64(const AStream: TStream): string;
var
EncodedStream: TStringStream;
Encoder: TBase64EncodingStream;
begin
EncodedStream := TStringStream.Create('');
Encoder := TBase64EncodingStream.Create(EncodedStream);
try
AStream.Position := 0;
Encoder.CopyFrom(AStream, AStream.Size);
Encoder.Flush;
Result := EncodedStream.DataString;
AStream.Position := 0;
finally
Encoder.Free;
EncodedStream.Free;
end;
end;
function Base64ToStream(const ABase64String: AnsiString): TStream;
var
DecodedStream: TBase64DecodingStream;
Base64Stream: TStringStream;
begin
Base64Stream := TStringStream.Create(ABase64String);
try
DecodedStream := TBase64DecodingStream.Create(base64stream);
try
Result := TMemoryStream.Create;
try
Result.CopyFrom(DecodedStream, DecodedStream.Size);
finally
Result.Position := 0;
end;
finally
DecodedStream.Free;
end;
finally
Base64Stream.Free;
end;
end;
function BGRABitmapToPNGStream(const ABGRABitmap: TBGRABitmap): TStream;
begin
Result := TMemoryStream.Create;
try
ABGRABitmap.SaveToStreamAsPng(Result);
finally
Result.Position := 0;
end;
end;
function BGRABitmapToBitmap(const ABGRABitmap: TBGRABitmap): TBitmap;
begin
Result := TBitmap.Create;
try
Result.PixelFormat := ABGRABitmap.Bitmap.PixelFormat;
Result.Transparent := ABGRABitmap.HasTransparentPixels or ABGRABitmap.HasSemiTransparentPixels;
Result.SetSize(ABGRABitmap.Width, ABGRABitmap.Height);
Result.Canvas.Lock;
try
Result.Canvas.Draw(0, 0, ABGRABitmap.Bitmap);
finally
Result.Canvas.Unlock;
end;
finally
end;
end;
procedure AssignBase64ToImage(const ABase64String: AnsiString; const AImage: TImage;
const AFastMode: Boolean = False);
var
BGRABitmap: TBGRABitmap;
Stream: TStream;
bmp: TBitmap;
begin
AImage.Picture.Clear;
Stream := Base64ToStream(ABase64String);
if (DetectFileFormat(Stream) <> ifUnknown) then
begin
BGRABitmap := TBGRABitmap.Create;
try
try
BGRABitmap.LoadFromStream(Stream);
finally
Stream.Free;
end;
if AFastMode then
begin
bmp := BGRABitmapToBitmap(BGRABitmap);
try
AImage.Transparent := bmp.Transparent;
AImage.Picture.Assign(bmp);
finally
bmp.Free;
end;
end
else
begin
Stream := BGRABitmapToPNGStream(BGRABitmap);
try
AImage.Transparent := BGRABitmap.HasTransparentPixels or BGRABitmap.HasSemiTransparentPixels;
AImage.Picture.PNG.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
finally
BGRABitmap.Free;
end;
end
else
Stream.Free;
end;
initialization
BGRASVG.RegisterSvgFormat;
BGRAOpenRaster.RegisterOpenRasterFormat;
BGRAPhoxo.RegisterPhoxoFormat;
BGRAPaintNet.RegisterPaintNetFormat;
end.