Last active
June 4, 2017 08:53
-
-
Save leizongmin/0c1f80f897580f168ebda1b4c42f519b to your computer and use it in GitHub Desktop.
go处理jpeg图片例子
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os" | |
"image/color" | |
"image/jpeg" | |
"image" | |
"time" | |
"fmt" | |
) | |
func main() { | |
if len(os.Args) < 3 { | |
panic("第一个参数为要处理的文件名,第二个参数为处理后要保存的文件名") | |
} | |
f, err := os.Open(os.Args[1]) | |
if err != nil { | |
panic(err) | |
} | |
ts := time.Now() | |
ts2 := ts | |
img, err2 := jpeg.Decode(f) | |
if err2 != nil { | |
panic(err2) | |
} | |
b := img.Bounds() | |
w := b.Dx() | |
h := b.Dy() | |
fmt.Printf("read:\t %dms\n", time.Since(ts) / 1000000) | |
ts = time.Now() | |
img2 := image.NewRGBA(image.Rect(0, 0, w, h)) | |
for x := 0; x < w; x++ { | |
for y := 0; y < h; y++ { | |
r, g, b, a := img.At(x, y).RGBA() | |
img2.Set(x, y, color.RGBA{uint8(255 - r >> 8), uint8(255 - g >> 8), uint8(255 - b >> 8), uint8(a >> 8) }) | |
//img2.Set(x, y, color.White) | |
} | |
} | |
fmt.Printf("convert:\t %dms\n", time.Since(ts) / 1000000) | |
ts = time.Now() | |
s, err := os.Create(os.Args[2]) | |
if err != nil { | |
panic(err) | |
} | |
err = jpeg.Encode(s, img2, &jpeg.Options{Quality: 75 }) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("save:\t %dms\n", time.Since(ts) / 1000000) | |
fmt.Printf("total:\t %dms\n", time.Since(ts2) / 1000000) | |
fmt.Printf("size:\t %dx%d", w, h) | |
} | |
/* | |
全白 | |
read: 245ms | |
convert: 939ms | |
save: 281ms | |
total: 1466ms | |
size: 4032x3024 | |
反色 | |
read: 251ms | |
convert: 1341ms | |
save: 382ms | |
total: 1974ms | |
size: 4032x3024 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment