-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_image.go
More file actions
87 lines (69 loc) · 1.6 KB
/
Copy pathprocess_image.go
File metadata and controls
87 lines (69 loc) · 1.6 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
package main
import (
"image"
"image/color"
"image/jpeg"
"image/png"
"log"
"os"
"path"
)
func processImage(fileName string) {
inputFile, err := os.Open(getInputPath(fileName))
if err != nil {
log.Fatal("Error opening file", err)
}
defer func(inputFile *os.File) {
err := inputFile.Close()
if err != nil {
log.Fatal("Error closing file", err)
}
}(inputFile)
outputFile, err := os.Create(getOutputPath(fileName))
if err != nil {
log.Fatal("Error creating file", err)
}
defer func(outputFile *os.File) {
err := outputFile.Close()
if err != nil {
log.Fatal("Error closing file", err)
}
}(outputFile)
ext := path.Ext(fileName)
var colorImage image.Image
switch ext {
case ".png":
colorImage, err = png.Decode(inputFile)
if err != nil {
log.Fatal("Error decoding image", err)
}
case ".jpg", ".jpeg":
colorImage, err = jpeg.Decode(inputFile)
if err != nil {
log.Fatal("Error decoding image", err)
}
default:
log.Fatal("Unsupported file type", ext)
}
grayImage := image.NewGray(colorImage.Bounds())
bounds := colorImage.Bounds()
height := bounds.Dy()
width := bounds.Dx()
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
r, g, b, _ := colorImage.At(x, y).RGBA()
white := (r + g + b) / 3
grayImage.Set(x, y, color.Gray{Y: uint8(white >> 8)})
}
}
err = png.Encode(outputFile, grayImage)
if err != nil {
log.Fatal("Error encoding image", err)
}
}
func getInputPath(fileName string) string {
return path.Join(InputDirectory, fileName)
}
func getOutputPath(fileName string) string {
return path.Join(OutputDirectory, fileName)
}