代码说明:
- Image 类型的选择:根据文件扩展名,代码会选择
TPngImage
或TJpegImage
来加载图片。 - 图像加载和调整大小:使用
TBitmap
将图像调整到指定的图标尺寸。 - 图标创建和保存:将位图分配给
TIcon
对象并保存为 .ico 文件。
使用说明:
- 将代码添加到您的 Delphi 项目中。
- 修改
ConvertToIcon
方法的输入文件路径和输出文件路径。 - 调用
ConvertToIcon
方法时,指定所需的图标大小(例如 16x16、32x32、64x64 等)。
运行该代码后,它会将指定的 .png 或 .jpg 文件转换为 .ico 文件,并保存到指定位置。
uses
Vcl.Graphics, Vcl.Imaging.pngimage, Vcl.Imaging.jpeg, Vcl.Imaging.GIFImg, System.SysUtils, System.Classes;
procedure ConvertToIcon(const SourceFile, DestFile: string; IconSize: Integer);
var
Image: TGraphic;
Icon: TIcon;
Bitmap: TBitmap;
Ext: string;
begin
// 获取文件扩展名并转换为小写
Ext := LowerCase(ExtractFileExt(SourceFile));
// 根据扩展名选择合适的图像加载器
if Ext = '.png' then
Image := TPngImage.Create
else if Ext = '.jpg' then
Image := TJpegImage.Create
else if Ext = '.bmp' then
Image := TBitmap.Create
else if Ext = '.gif' then
Image := TGIFImage.Create
else
raise Exception.Create('Unsupported file format.');
try
// 加载图像文件
Image.LoadFromFile(SourceFile);
// 创建位图并调整大小
Bitmap := TBitmap.Create;
try
Bitmap.PixelFormat := pf32bit;
Bitmap.SetSize(IconSize, IconSize);
Bitmap.Canvas.StretchDraw(Rect(0, 0, IconSize, IconSize), Image);
// 创建图标并分配位图
Icon := TIcon.Create;
try
Icon.Assign(Bitmap);
Icon.SaveToFile(DestFile);
finally
Icon.Free;
end;
finally
Bitmap.Free;
end;
finally
Image.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ConvertToIcon('C:\path\to\input.png', 'C:\path\to\output.ico', 64);
end;
下面是改进的方法:
procedure ConvertToIcon(const SourceFile, DestFile: string; IconSize: Integer);
var
Image: TGraphic;
Icon: TIcon;
Bitmap: TBitmap;
maskBmp:TBitmap;
Ext: string;
TM : TImageList;
begin
// 获取文件扩展名并转换为小写
Ext := LowerCase(ExtractFileExt(SourceFile));
// 根据扩展名选择合适的图像加载器
if Ext = '.png' then
Image := TPngImage.Create
else if Ext = '.jpg' then
Image := TJpegImage.Create
else if Ext = '.bmp' then
Image := TBitmap.Create
else if Ext = '.gif' then
Image := TGIFImage.Create
else
raise Exception.Create('Unsupported file format.');
try
// 加载图像文件
Image.LoadFromFile(SourceFile);
// 创建位图并调整大小
Bitmap := TBitmap.Create;
maskBMP:=TBitmap.create;
TM := TImageList.Create(nil);
try
Bitmap.PixelFormat := pf32bit;
Bitmap.SetSize(IconSize, IconSize);
Bitmap.Canvas.StretchDraw(Rect(0, 0, IconSize, IconSize), Image);
// Bitmap.Transparent := True;
// Bitmap.TransparentColor := clWhite;
// Bitmap.TransparentMode := tmAuto;
maskBMP.width :=IconSize;
MaskBmp.height:=IconSize;
maskBMp.canvas.brush.color := clred;
maskBmp.canvas.fillrect(Rect(0,0,IconSize,IconSize));
//maskBMp.Transparent := True;
//maskBMp.TransparentColor := 0;
//maskBMp.TransparentMode := tmAuto;
TM.width :=IconSize;
TM.height:=IconSize;
TM.add(Bitmap,nil);
// 创建图标并分配位图
Icon := TIcon.Create;
try
TM.GetIcon(0,Icon);
Icon.SaveToFile(DestFile);
finally
Icon.Free;
end;
finally
Bitmap.Free;
maskBMp.Free;
TM.Free;
end;
finally
Image.Free;
end;
end;