-
Notifications
You must be signed in to change notification settings - Fork 5
/
jpg_to_bytes.go
84 lines (78 loc) · 1.41 KB
/
jpg_to_bytes.go
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
/*
* The code is automatically generated by the Goland.
* Copyright © Aquarian-Age. All Rights Reserved.
* Licensed under MIT.
*/
package cmd
import (
"bytes"
"fmt"
"image/jpeg"
"image/png"
"io"
"log"
"os"
)
// JpgToBytes name(/a/b/aaa.jgp)
func JpgToBytes(name string) (error, []byte) {
f, err := os.Open(name)
if err != nil {
log.Println(err)
}
buf := bytes.NewBuffer(nil)
if _, err := io.Copy(buf, f); err != nil {
log.Println(err)
}
err = f.Close()
if err != nil {
return err, nil
}
byteFile := buf.Bytes()
return nil, byteFile
}
// ByteToJpg 字节转jpg
func ByteToJpg(byteFile []byte, path, name string) {
r := bytes.NewReader(byteFile)
img, err := jpeg.Decode(r)
if err != nil {
log.Println(err)
}
fileName := path + name
out, err := os.Create(fileName)
if err != nil {
fmt.Println(err)
}
defer func(out *os.File) {
err := out.Close()
if err != nil {
log.Println(err)
}
}(out)
err = jpeg.Encode(out, img, nil)
if err != nil {
return
}
}
// ByteToPng 字节转png
func ByteToPng(byteFile []byte, path, name string) {
r := bytes.NewReader(byteFile)
img, err := png.Decode(r)
if err != nil {
log.Println(err)
}
fileName := path + name
out, err := os.Create(fileName)
if err != nil {
fmt.Println(err)
}
defer func(out *os.File) {
err := out.Close()
if err != nil {
log.Println(err)
}
}(out)
err = png.Encode(out, img)
if err != nil {
return
}
}