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))
}
|