/
fromkmeg.go
109 lines (77 loc) · 2.36 KB
/
fromkmeg.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
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
package main
import (
"context"
"errors"
"flag"
"image"
"image/jpeg"
"image/png"
"io"
"os"
"path/filepath"
ew "github.com/pkg/errors"
"github.com/rameshputalapattu/kmeg"
)
//FromkmegCommand Command to convert images from png format to kmeg binary format
type FromkmegCommand struct {
Params *CmdParams
}
const fromKmegHelp = `convert a image into kmeg format`
//Name Gives the command Name
func (cmd *FromkmegCommand) Name() string { return "fromKmeg" }
//Args returns the command args
func (cmd *FromkmegCommand) Args() string { return "" }
//ShortHelp returns short help text
func (cmd *FromkmegCommand) ShortHelp() string { return fromKmegHelp }
//LongHelp returns long help text
func (cmd *FromkmegCommand) LongHelp() string { return fromKmegHelp }
//Hidden returns whether it is a hidden command
func (cmd *FromkmegCommand) Hidden() bool { return false }
//Register Registers the flag set
func (cmd *FromkmegCommand) Register(fs *flag.FlagSet) {
}
//Run Run the ToKmeg command to convert a image into kmeg binary format
func (cmd *FromkmegCommand) Run(ctx context.Context, args []string) error {
if len(cmd.Params.SrcImageFile) == 0 {
return errors.New("Source Image file should be provided for tokmeg")
}
if len(cmd.Params.DstImageFile) == 0 {
return errors.New("Destination Image file should be provided for tokmeg")
}
return decompress(cmd.Params.SrcImageFile, cmd.Params.DstImageFile)
}
func writeImage(img *image.RGBA, w io.Writer, extn string) error {
switch extn {
case ".png":
err := png.Encode(w, img)
return err
case ".jpg", ".JPEG", ".jpeg", ".JPG":
err := jpeg.Encode(w, img, &jpeg.Options{Quality: 100})
return err
default:
return errors.New("not a valid extension")
}
}
func decompress(decompName string, reconstName string) error {
r, err := os.Open(decompName)
if err != nil {
return ew.Wrap(err, "opening the .kmeg file for reading failed")
}
w, err := os.Create(reconstName)
if err != nil {
return ew.Wrap(err, "creating the file to write re-constructed image failed")
}
defer w.Close()
kmegImg, err := kmeg.Decode(r)
if err != nil {
return ew.Wrap(err, "Decoding kmeg to rgb image failed")
}
rgb := kmeg.Inflate(kmegImg)
rgba := kmeg.ConvertToRGBA(rgb)
ext := filepath.Ext(reconstName)
err = writeImage(rgba, w, ext)
if err != nil {
return ew.Wrap(err, "encoding to png format failed")
}
return nil
}