go 读取BMP文件头

Posted saryli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go 读取BMP文件头相关的知识,希望对你有一定的参考价值。

BMP文件头定义:

WORD 两个字节 16bit

DWORD 四个字节 32bit

技术图片

package main

import (
	"encoding/binary"
	"fmt"
	"os"
)

func main() 
	file, err := os.Open("tim.bmp")
	if err != nil 
		fmt.Println(err)
		return
	

	defer file.Close()

	//type拆成两个byte来读
	var headA, headB byte
	//Read第二个参数字节序一般windows/linux大部分都是LittleEndian,苹果系统用BigEndian
	binary.Read(file, binary.LittleEndian, &headA)
	binary.Read(file, binary.LittleEndian, &headB)

	//文件大小
	var size uint32
	binary.Read(file, binary.LittleEndian, &size)

	//预留字节
	var reservedA, reservedB uint16
	binary.Read(file, binary.LittleEndian, &reservedA)
	binary.Read(file, binary.LittleEndian, &reservedB)

	//偏移字节
	var offbits uint32
	binary.Read(file, binary.LittleEndian, &offbits)

	fmt.Println(headA, headB, size, reservedA, reservedB, offbits)


  执行结果

66 77 196662 0 0 54

 

 

使用结构体方式

package main

import (
	"encoding/binary"
	"fmt"
	"os"
)

type BitmapInfoHeader struct 
	Size           uint32
	Width          int32
	Height         int32
	Places         uint16
	BitCount       uint16
	Compression    uint32
	SizeImage      uint32
	XperlsPerMeter int32
	YperlsPerMeter int32
	ClsrUsed       uint32
	ClrImportant   uint32


func main() 
	file, err := os.Open("tim.bmp")
	if err != nil 
		fmt.Println(err)
		return
	

	defer file.Close()

	//type拆成两个byte来读
	var headA, headB byte
	//Read第二个参数字节序一般windows/linux大部分都是LittleEndian,苹果系统用BigEndian
	binary.Read(file, binary.LittleEndian, &headA)
	binary.Read(file, binary.LittleEndian, &headB)

	//文件大小
	var size uint32
	binary.Read(file, binary.LittleEndian, &size)

	//预留字节
	var reservedA, reservedB uint16
	binary.Read(file, binary.LittleEndian, &reservedA)
	binary.Read(file, binary.LittleEndian, &reservedB)

	//偏移字节
	var offbits uint32
	binary.Read(file, binary.LittleEndian, &offbits)

	fmt.Println(headA, headB, size, reservedA, reservedB, offbits)

	infoHeader := new(BitmapInfoHeader)
	binary.Read(file, binary.LittleEndian, infoHeader)
	fmt.Println(infoHeader)


  执行结果:

66 77 196662 0 0 54

&40 256 256 1 24 0 196608 3100 3100 0 0

以上是关于go 读取BMP文件头的主要内容,如果未能解决你的问题,请参考以下文章

用标准c读取bmp文件的长宽?

Bmp图像的数据格式及读取

读bmp图片:头文件为66字节。。。怎么用c语言来读取数据啊,网上的代码我看不懂。新手,希望能写明白些

关于BMP

读取 BMP 标头,打包。读取不正确的值

读取 BMP 文件 C++(读取 BMP 标头时出现问题)