GO语言将多个图片的base64合并为一张图,并返回新的base64

GO语言将多个图片的base64合并为一张图,并返回新的base64

package utils

import (
"bytes"
"encoding/base64"
"image"
"image/draw"
"image/jpeg"
"strings"
)

// MergeImagesToBase64 将多个图片base64串合并为一个图片base64串
//
// 参数:
// imageBase64List []string:多个图片base64串
//
// 返回值:
// string:合并后的图片base64串
// error:错误信息,如果合并成功则返回nil
func MergeImagesToBase64(imageBase64List []string) (string, error) {
// 存储所有图像的切片
var images []*image.RGBA
// 存储所有图像的总高度
totalHeight := 0
// 存储所有图像的最大宽度
maxWidth := 0

// 遍历所有图像的base64字符串
for _, base64Str := range imageBase64List {
// 解码base64字符串为图像
reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(base64Str))
img, _, err := image.Decode(reader)
if err != nil {
return "", err
}

// 创建一个新的RGBA图像,并复制原始图像到新图像中
rgba := image.NewRGBA(image.Rect(0, 0, img.Bounds().Dx(), img.Bounds().Dy()))
draw.Draw(rgba, rgba.Bounds(), img, img.Bounds().Min, draw.Src)

// 将新图像添加到切片中
images = append(images, rgba)

// 更新最大宽度和总高度
if img.Bounds().Dx() > maxWidth {
maxWidth = img.Bounds().Dx()
}
totalHeight += img.Bounds().Dy()
}

// 创建一个新的RGBA图像,大小为所有图像的最大宽度和总高度
mergedImg := image.NewRGBA(image.Rect(0, 0, maxWidth, totalHeight))

// 遍历所有图像,将它们复制到合并图像中
yOffset := 0
for _, img := range images {
draw.Draw(mergedImg, image.Rect(0, yOffset, img.Bounds().Dx(), yOffset+img.Bounds().Dy()), img, image.Point{0, 0}, draw.Src)
yOffset += img.Bounds().Dy()
}

// 将合并图像编码为JPEG格式的字节缓冲区
var buf bytes.Buffer
if err := jpeg.Encode(&buf, mergedImg, nil); err != nil {
return "", err
}

// 将字节缓冲区转换为base64字符串格式的编码字符串
encodedStr := base64.StdEncoding.EncodeToString(buf.Bytes())

return encodedStr, nil
}


最后编辑于:2024/01/08作者: 牛逼PHP

发表评论