我已使用go-fitz将pdf转换为jpeg,这为我提供了目录中jpeg的列表。我正在从目录中读取图像列表,然后尝试将它们组合成一个图像。该图像为jpeg类型,如果我仅使用第1页和第2页使用索引,则该图像可以部分工作。我想将pdf页面jpeg图像拼接回一个jpeg图像。代码的最终结果将在第一页生成单个图像。
Golang how to concatenate/append images to one another
如果我使用图像索引0和1,则此代码有效。但是不能在我的代码的动态列表中使用。但是,我将获得一个动态图像列表,需要将它们放到一个图像中。我假设它与最终图像画布大小有关,并将其添加到画布中。当我尝试使用流程叠加示例时,代码最终将第一页和最后一页放在宽阔的画布中,而缺少其余页面。
package converter
import (
"fmt"
"image"
"image/draw"
"image/jpeg"
"os"
"path/filepath"
"strings"
log "github.com/sirupsen/logrus"
)
func openAndDecode(imgPath string) image.Image {
img, err := os.Open(imgPath)
if err != nil {
log.Fatalf("Failed to open %s", err)
}
decoded, _, err := image.Decode(img)
if err != nil {
log.Fatalf("Failed to decode %s", err)
}
defer img.Close()
return decoded
}
// StichImages takes a directory of images and combine them into a single image
func StichImages(dirPath string) {
fileList := []string{}
decodedImages := []image.Image{}
err := filepath.Walk(dirPath, func(path string, f os.FileInfo, err error) error {
fileList = append(fileList, path)
return nil
})
if err != nil {
log.Fatal(err)
}
// If there is only one image in folder no need to stich
if len(fileList) == 1 {
return
}
for _, filePath := range fileList {
if strings.Contains(filePath, ".jpg") {
decodedImage := openAndDecode(filePath)
decodedImages = append(decodedImages, decodedImage)
}
}
outPutPath := filepath.Join(dirPath, "output.jpg")
if len(decodedImages) == 0 {
log.Error(fmt.Sprintf("No images found in: %s", dirPath))
}
//starting position of the second image (bottom left)
startingPoint := image.Point{}
finalImageCanvas := image.Rectangle{image.Point{0, 0}, decodedImages[0].Bounds().Max}
rgba := image.NewRGBA(finalImageCanvas)
for index, newImage := range decodedImages {
if index == 0 {
startingPoint = image.Point{newImage.Bounds().Dx(), 0}
draw.Draw(rgba, newImage.Bounds(), newImage, image.Point{0, 0}, draw.Src)
} else {
newImageRect := image.Rectangle{startingPoint, startingPoint.Add(newImage.Bounds().Size())}
finalImageCanvas = image.Rectangle{image.Point{0, 0}, newImageRect.Max}
draw.Draw(rgba, newImageRect, newImage, image.Point{0, 0}, draw.Src)
startingPoint = image.Point{newImageRect.Bounds().Dx(), 0}
}
}
out, err := os.Create(outPutPath)
if err != nil {
fmt.Println(err)
}
var opt jpeg.Options
opt.Quality = 80
jpeg.Encode(out, rgba, &opt)
}