main.go - randomcrap - random crap programs of varying quality
(HTM) git clone git://git.codemadness.org/randomcrap
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
main.go (1085B)
---
1 /* image to grayscale */
2
3 package main
4
5 import (
6 "image"
7 "image/color"
8 "image/jpeg"
9 "image/png"
10 "os"
11 )
12
13 func round(f float64) float64 {
14 f += 0.5
15 f *= 10
16 return float64(int64(f) / 10)
17 }
18
19 func main() {
20 file, err := os.Open("test.jpg")
21 if err != nil {
22 panic(err)
23 }
24 defer file.Close()
25
26 img, err := jpeg.Decode(file)
27 if err != nil {
28 panic(err)
29 }
30
31 out, err := os.OpenFile("output.png", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
32 if err != nil {
33 panic(err)
34 }
35 defer out.Close()
36
37 b := img.Bounds()
38 w := b.Max.X
39 h := b.Max.Y
40
41 newimg := image.NewNRGBA(image.Rect(0, 0, w, h))
42
43 for y := 0; y < h; y++ {
44 for x := 0; x < w; x++ {
45 c := img.At(x, y)
46 r, g, b, _ := c.RGBA()
47
48 // NOTE: linear conversion, a fancier way could be:
49 // v = 0.2126 * r + 0.7152 * g + 0.0722 * b;
50 avg := float64(r+g+b) / 3.0
51 avg /= 257.0
52 avg = round(avg)
53
54 r8 := uint8(avg)
55 g8 := uint8(avg)
56 b8 := uint8(avg)
57
58 newimg.Set(x, y, color.NRGBA{
59 R: r8,
60 G: g8,
61 B: b8,
62 A: 255,
63 })
64 }
65 }
66
67 err = png.Encode(out, newimg)
68 if err != nil {
69 panic(err)
70 }
71 }