源码分享-golang的BMP文件读写库

本文详细介绍了如何使用Go语言实现BMP文件的读写功能,包括BitmapFile结构定义、文件头处理、数据读写方法以及保存函数。代码示例展示了如何创建和操作BMP图像文件。
摘要由CSDN通过智能技术生成

用于读写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.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值