ICO文件格式
存放在github.com上的源代码链接
Go语言处理Windows系统的图标ICO文件(上)
Go语言处理Windows系统的图标ICO文件(中)
将PNG或BMP转换为ICO文件
在前面的两章中,我们初探了ico文件的结构,并且完成了将ico文件中的bmp和png数据提取出来的功能,在本章中,我们来看看如何将bmp或png转换成png图片。
这里看看运行后的效果:
在下面这个URL链接中可以获取本教程内容的ico图标文件资源:
<ico文件下载>
先修改之前的定义:
// 定义常量
// Constant definition
const (
typeUKN = iota // unknow type
typeBMP // bmp file
typePNG // png file
fileHeaderSize = 6 // 文件头的大小
pngFileHeaderSize = 8 // png文件头大小
headerSize = 16 // icon图标的头结构大小
bitmapHeaderSize = 14 // 位图文件头
dibHeaderSize = 40 // dib结构头
)
// 定义变量
// Variable definitions
var (
// 错误信息
ErrIcoInvalid = errors.New("ico: Invalid icon file") // 无效的ico文件
ErrIcoReaders = errors.New("ico: Reader type is not os.File pointer") // LoadIconFile的io.Reader参数不是文件指针
ErrIcoFileType = errors.New("ico: Reader is directory, not file") // io.Reader的文件指针是目录,不是文件
ErrIconsIndex = errors.New("ico: Slice out of bounds") // 读取ico文件时,可能出现的切片越界错误
PNGHEADER = []byte{
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A} // PNG 文件头
DIBHEADER = []byte{
0x28, 0, 0, 0} // DIB 头
BMPHEADERID = []byte{
0x42, 0x4d}
)
// 类型定义 type definition
// 定义icon图标数据的类型
// Define the type of icon data
type (
ICONTYPE int
WinIconData []byte
WinIconStruct []winIconStruct
)
// 定义 Windows 系统的 Ico 文件结构
// Defining the Ico file structure of Windows system
type WinIcon struct {
fileHeader *winIconFileHeader // 文件头
icos WinIconStruct // icon 头结构
}
// ico文件头结构
// 参考维基百科:
// https://en.wikipedia.org/wiki/ICO_(file_format)
type winIconFileHeader struct {
ReservedA uint16 // 保留字段,始终为 '0x0000'
FileType uint16 // 图像类型:'0x0100' 为 ico,'0x0200' 为 cur
ImageCount uint16 // 图像数量:至少为 '0x0100' 即 1个图标
}
// icon图标头结构
// 参考维基百科:
// https://en.wikipedia.org/wiki/ICO_(file_format)
type winIconStruct struct {
Width uint8 // 图像宽度
Height uint8 // 图像高度
Palette uint8 // 调色板颜色数,不使用调色版为 '0x00'
ReservedB uint8 // 保留字段,始终为 '0x00'
ColorPlanes uint16 // 在ico中,指定颜色平面,'0x0000' 或则 '0x0100'
BitsPerPixel uint16