将图片压缩后转Base64函数

function CutImgToBase(fn: string): string;  // 压缩图片只能压缩bmp:将jpg转换成bmp再压缩
var
m1: TMemoryStream;
m2: TStringStream;
jpg: TJPEGImage;
bmp: TBitmap;
begin
jpg := TJpegImage.Create;
bmp := TBitmap.Create;
m1 := TMemoryStream.Create;
m2 := TStringStream.Create;
jpg.LoadFromFile(fn);
bmp.Width := jpg.Width div 2;
bmp.Height := jpg.Height div 2;
bmp.Canvas.StretchDraw(bmp.Canvas.ClipRect, jpg);
jpg.Assign(bmp);
jpg.CompressionQuality := 30;
jpg.Compress; // 先指定大小再压缩
jpg.SaveToStream(m1);
m1.Position := 0; // 一定要还原指针,才能base64
EncdDecd.EncodeStream(m1, m2);
result := m2.DataString.Replace(#13, '').Replace(#10, '');
bmp.Free;
jpg.Free;
m1.Free;
m2.Free;
end;

调用函数:

procedure TForm2.Button4Click(Sender: TObject);   // 调用函数  压缩并编码
var
m: TStringStream;
s: string;
begin
s := CutImgToBase('test.jpg');
FilePutContents('mm.txt', s);
m := TStringStream.Create(s);
Memo1.Lines.Add(m.DataString);
m.SaveToFile('base64.txt');
end;

解码Base64测试:

procedure TForm2.DecodeBaseClick(Sender: TObject);   // 解码
var
m1: TStringStream;
m2: TMemoryStream;
begin
m1 := TStringStream.Create;
m2 := TMemoryStream.Create;
m1.LoadFromFile('base64.txt');
EncdDecd.DecodeStream(m1, m2);
m2.SaveToFile('1.jpg');
m1.Free;
m2.Free;
end;
上一篇:Kubernetes(k8s)完整安装教程


下一篇:linux安装python