forked from IBM/CodeEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjob.go
97 lines (82 loc) · 2.04 KB
/
job.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
package main
import (
"bytes"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
"image/png"
"log"
"os"
"strings"
cosclient "github.com/duglin/cosclient/client"
"github.com/nfnt/resize"
)
func MakeThumbnail(inBuf []byte) ([]byte, error) {
inImage, _, err := image.Decode(bytes.NewReader(inBuf))
if err != nil {
return nil, fmt.Errorf("Error decoding image: %s", err)
}
buf := &bytes.Buffer{}
// resize to width using Lanczos resampling
// and preserve aspect ratio
thumb := resize.Resize(50, 50, inImage, resize.Lanczos3)
err = png.Encode(buf, thumb)
if err != nil {
return nil, fmt.Errorf("Error shrinking image: %s", err)
}
return buf.Bytes(), nil
}
func CalcThumbnails(bucketName string) error {
apiKey := os.Getenv("CLOUD_OBJECT_STORAGE_APIKEY")
svcID := os.Getenv("CLOUD_OBJECT_STORAGE_RESOURCE_INSTANCE_ID")
COSClient, err := cosclient.NewClient(apiKey, svcID)
if err != nil {
return err
}
objs, err := COSClient.ListObjects(bucketName)
if err != nil {
return err
}
names := []string{}
thumbs := map[string]bool{}
for _, obj := range objs {
if strings.HasSuffix(obj.Key, "-thumb") {
thumbs[obj.Key] = true
continue
}
names = append(names, obj.Key)
}
for _, name := range names {
if _, ok := thumbs[name+"-thumb"]; !ok {
log.Printf("Processing: %s", name)
image, err := COSClient.DownloadObject(bucketName, name)
if err != nil {
return fmt.Errorf("Error downloading %q: %s", name, err)
}
thumb, err := MakeThumbnail(image)
if err == nil {
err = COSClient.UploadObject(bucketName, name+"-thumb", thumb)
if err != nil {
return fmt.Errorf("Error uploading %q:%s", name+"-thumb",
err)
} else {
log.Printf("Added: %s", name+"-thumb")
}
} else {
return fmt.Errorf("Error processing %q: %s", name, err)
}
}
}
return nil
}
func main() {
bucketName := os.Getenv("BUCKET")
if bucketName == "" {
bucketName = "ce-images"
}
if err := CalcThumbnails(bucketName); err != nil {
fmt.Fprintf(os.Stderr, "Error calculating thumbnails: %s\n", err)
os.Exit(1)
}
}