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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值