/
MustResizePngFileToHeightAndWidth.go
72 lines (66 loc) · 1.8 KB
/
MustResizePngFileToHeightAndWidth.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
package udwImageResize
import (
"bytes"
"github.com/tachyon-protocol/udw/udwFile"
"image"
_ "image/gif"
_ "image/jpeg"
"image/png"
_ "image/png"
)
type MustResizePngFileToHeightAndWidthRequest struct {
InFilePath string
OutFilePath string
Height int
Width int
}
func MustResizePngFileToHeightAndWidth(req MustResizePngFileToHeightAndWidthRequest) {
if req.OutFilePath == "" && req.InFilePath != "" {
req.OutFilePath = req.InFilePath
}
fileContent := udwFile.MustReadFile(req.InFilePath)
inputImage, _, err := image.Decode(bytes.NewBuffer(fileContent))
if err != nil {
panic(err)
}
if inputImage.Bounds().Dx() == req.Width && inputImage.Bounds().Dy() == req.Height {
udwFile.MustWriteFile(req.OutFilePath, fileContent)
return
}
MustResizeGoImageToPngFile(MustResizeGoImageToPngFileRequest{
Height: req.Height,
Width: req.Width,
Image: inputImage,
OutFilePath: req.OutFilePath,
})
}
func MustResizePngFileSelfToRate(filepath string, rate float64) {
fileContent := udwFile.MustReadFile(filepath)
inputImage, _, err := image.Decode(bytes.NewBuffer(fileContent))
if err != nil {
panic(err)
}
MustResizeGoImageToPngFile(MustResizeGoImageToPngFileRequest{
Height: int(float64(inputImage.Bounds().Dy()) * rate),
Width: int(float64(inputImage.Bounds().Dx()) * rate),
Image: inputImage,
OutFilePath: filepath,
})
}
func MustResizePngContentToSquare(pngContent []byte, width int) (outPngContent []byte) {
inputImage, _, err := image.Decode(bytes.NewBuffer(pngContent))
if err != nil {
panic(err)
}
outImage := MustResizeGoImageToGoImage(MustResizeGoImageToGoImageRequest{
Width: width,
Height: width,
InImage: inputImage,
})
buf := &bytes.Buffer{}
err = png.Encode(buf, outImage)
if err != nil {
panic(err)
}
return buf.Bytes()
}