-
Notifications
You must be signed in to change notification settings - Fork 7
/
img_generation.go
76 lines (65 loc) · 1.31 KB
/
img_generation.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
package main
import (
"bytes"
"context"
"image"
"image/png"
"os"
"os/user"
"path/filepath"
"github.com/devinyf/dashscopego"
"github.com/devinyf/dashscopego/wanx"
)
func main() {
model := wanx.WanxV1
token := os.Getenv("DASHSCOPE_API_KEY")
if token == "" {
panic("token is empty")
}
cli := dashscopego.NewTongyiClient(model, token)
req := &wanx.ImageSynthesisRequest{
// Model: "wanx-v1",
Model: model,
Input: wanx.ImageSynthesisInput{
Prompt: "A beautiful sunset",
},
Params: wanx.ImageSynthesisParams{
N: 1,
},
// 是否下载图片, 默认不下载,仅获取url
Download: true,
}
ctx := context.TODO()
imgBlobs, err := cli.CreateImageGeneration(ctx, req)
if err != nil {
panic(err)
}
for _, blob := range imgBlobs {
// 查看生成的图片url
//nolint:forbidigo
print(blob.ImgURL)
// 下载图片到桌面
if req.Download {
saveImg2Desktop(blob.ImgType, blob.Data)
}
}
}
func saveImg2Desktop(_ string, data []byte) {
buf := bytes.NewBuffer(data)
img, _, err := image.Decode(buf)
if err != nil {
panic(err)
}
usr, err := user.Current()
if err != nil {
panic(err)
}
f, err := os.Create(filepath.Join(usr.HomeDir, "Desktop", "wanx_image.png"))
if err != nil {
panic(err)
}
defer f.Close()
if err := png.Encode(f, img); err != nil {
panic(err)
}
}