用于读写BMP文件的golang版源码
源码基于源码分享-golang的二进制文件读写库 https://blog.csdn.net/zhyulo/article/details/128890546
BMP文件格式可参考位图文件解析-位图(bmp)、图标(ico)与光标(cur) https://blog.csdn.net/zhyulo/article/details/85934728
import (
"binary"
"bufio"
"errors"
"fmt"
"os"
)
var ofb = errors.New("out of bound")
type BitmapFile struct {
Header BitmapFileHeader
Info BitmapInfoHeader
Quad BitmapQuad `info:"调色板"`
BitLines BitmapLines `info:"点阵数据"`
}
func ReadBitmapFile(path string) (*BitmapFile, error) {
buf, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var bmp BitmapFile
err = binary.Unmarshal(buf, false, &bmp)
return &bmp, err
}
func NewBitmapFile(width, height int32, bitCount uint16) *BitmapFile {
bmp := &BitmapFile{
Header: BitmapFileHeader{
Type: MagicBmp{
'B', 'M'}},
Info: BitmapInfoHeader{
Size: 40,
Width: width,
Height: height,
Planes: 1,
BitCount: bitCount,
},
}
if height < 0 {
height = -height
}
bmp.BitLines = make(BitmapLines, height, height)
bytePerLine := (int32(bitCount)*width + 31) / 32 * 4
for i := int32(0); i < height; i++ {
bmp.BitLines[i] = make(BitmapLine, bytePerLine, bytePerLine)
}
bmp.Info.SizeImage = uint32(bytePerLine * height)
if bitCount < 16 {
bmp.Info.ClrUsed = 1 << bitCount
bmp.Quad = make(BitmapQuad, bmp.Info.ClrUsed, bmp.Info.ClrUsed)
}
bmp.Header.OffBits = 14 + bmp.Info.Size + uint32(len(bmp.Quad))*4
bmp.