Featured image of post 在Golang中操作图片

在Golang中操作图片

golang原生自带图片操作的image库, 可以通过这个库实现绘图.

# 绘制一个400*300的白底

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func main() {
	// 创建一张400*300的图片, 底图默认是透明
	img := image.NewRGBA(image.Rect(0, 0, 400, 300))
	// 将背景填充为白色
	point := img.Bounds().Size()
	for x := 0; x < point.X; x++ {
		for y := 0; y < point.Y; y++ {
			img.Set(x, y, color.White)
		}
	}
	// 保存图片
	file := must(os.Create("white.png"))
	defer file.Close()
	must_(png.Encode(file, img))
}

# 将多张图片垂直合并

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
func main() {
	// 将需要垂直合并的图片先载入
	images := make([]image.Image, 2)
	images[0] = must(jpeg.Decode(bytes.NewReader(must(os.ReadFile("1.jpg")))))
	images[1] = must(jpeg.Decode(bytes.NewReader(must(os.ReadFile("2.jpg")))))
	// 计算所需画布大小
	var maxWidth, maxHeight int
	for _, item := range images {
		pt := item.Bounds().Size()
		if pt.X > maxWidth {
			maxWidth = pt.X
		}
		maxHeight += pt.Y
	}
	// 创建一张画布
	img := image.NewRGBA(image.Rect(0, 0, maxWidth, maxHeight))
	var currentHeight int
	for _, item := range images {
		pt := item.Bounds().Size()
		draw.Draw(img, image.Rect(0, currentHeight, pt.X, currentHeight+pt.Y), item, image.Point{}, draw.Over)
		currentHeight += pt.Y
	}
	// 保存图片
	file := must(os.Create("merger.png"))
	defer file.Close()
	writer := bufio.NewWriter(file)
	defer writer.Flush()
	must_(png.Encode(writer, img))
}

# 将多张图片垂直合并-自动缩放

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 缩放的核心是引用开源库实现: https://github.com/nfnt/resize
func main() {
	// 将需要垂直合并的图片先载入
	images := make([]image.Image, 2)
	images[0] = must(jpeg.Decode(bytes.NewReader(must(os.ReadFile("1.jpg")))))
	images[1] = must(jpeg.Decode(bytes.NewReader(must(os.ReadFile("2.jpg")))))
	var minWidth, maxHeight int
	// 计算画布宽度
	for _, item := range images {
		pt := item.Bounds().Size()
		if minWidth == 0 || pt.X < minWidth {
			minWidth = pt.X
		}
	}
	// 缩放宽度不匹配的图片, 并计算画布高度
	for i, item := range images {
		pt := item.Bounds().Size()
		if pt.X != minWidth {
			newHeight := uint(float64(pt.Y) * float64(minWidth) / float64(pt.X))
			images[i] = resize.Resize(uint(minWidth), newHeight, item, resize.Lanczos3)
			maxHeight += int(newHeight)
		} else {
			maxHeight += pt.Y
		}
	}
	// 创建一张画布
	img := image.NewRGBA(image.Rect(0, 0, minWidth, maxHeight))
	var currentHeight int
	for _, item := range images {
		pt := item.Bounds().Size()
		draw.Draw(img, image.Rect(0, currentHeight, pt.X, currentHeight+pt.Y), item, image.Point{}, draw.Over)
		currentHeight += pt.Y
	}
	// 保存图片
	file := must(os.Create("merger.png"))
	defer file.Close()
	writer := bufio.NewWriter(file)
	defer writer.Flush()
	must_(png.Encode(writer, img))
}