-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathutil.go
More file actions
114 lines (95 loc) · 2.39 KB
/
util.go
File metadata and controls
114 lines (95 loc) · 2.39 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package examples
import (
"image"
"image/draw"
"image/png"
"log"
"os"
"github.com/unidoc/unipdf/v4/model"
"github.com/unidoc/unipdf/v4/render"
)
func RenderPDFToImage(filename string) {
// Create reader.
file, err := os.Open(filename)
if err != nil {
log.Fatalf("Could not open pdf file: %v", err)
}
defer file.Close()
reader, err := model.NewPdfReader(file)
if err != nil {
log.Fatalf("Could not create reader: %v", err)
}
// Render pages.
device := render.NewImageDevice()
device.OutputWidth = 2000
// Get page.
page, err := reader.GetPage(1)
if err != nil {
log.Fatalf("Could not retrieve page: %v", err)
}
// Render page to PNG file.
err = device.RenderToPath(page, "preview.png")
if err != nil {
log.Fatalf("Image rendering error: %v", err)
}
cropImage("preview.png")
}
func cropImage(imagePath string) {
// Open the input image
file, err := os.Open(imagePath)
if err != nil {
log.Fatal(err)
}
defer file.Close()
img, err := png.Decode(file)
if err != nil {
log.Fatal(err)
}
// Find the bounding box of the non-empty (foreground) region
boundingBox := findBoundingBox(img)
// Crop the image using the bounding box
// Create a new RGBA image with the cropped dimensions
croppedImg := image.NewRGBA(image.Rect(0, 0, boundingBox.Dx(), boundingBox.Dy()))
// Draw the cropped section onto the new image
draw.Draw(croppedImg, croppedImg.Bounds(), img, boundingBox.Min, draw.Src)
// Save the cropped image
outFile, err := os.Create(imagePath)
if err != nil {
log.Fatal(err)
}
defer outFile.Close()
err = png.Encode(outFile, croppedImg)
if err != nil {
log.Fatal(err)
}
}
func findBoundingBox(img image.Image) image.Rectangle {
bounds := img.Bounds()
minX, maxX := bounds.Dx(), 0
minY, maxY := bounds.Dy(), 0
boundPadding := 100
// Iterate over each pixel to find the bounding box
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
pixelColor := img.At(x, y)
r, g, b, a := pixelColor.RGBA()
if r != 65535 || g != 65535 || b != 65535 || a != 65535 {
if x < minX {
minX = x
}
if x > maxX {
maxX = x
}
if y < minY {
minY = y
}
if y > maxY {
maxY = y
}
}
}
}
// Define the bounding box based on the min and max values
boundingBox := image.Rect(minX-boundPadding, minY-boundPadding, maxX+boundPadding+1, maxY+boundPadding+1)
return boundingBox
}