从已有签到背景中,复制出一张图片
(picFile string)
| 375 | |
| 376 | // 从已有签到背景中,复制出一张图片 |
| 377 | func copyImage(picFile string) (err error) { |
| 378 | // 读取目录中的文件列表,并随机挑选出一张图片 |
| 379 | cachePath := engine.DataFolder() + "cache/" |
| 380 | files, err := os.ReadDir(cachePath) |
| 381 | if err != nil { |
| 382 | return err |
| 383 | } |
| 384 | |
| 385 | // 随机取10次图片,取到图片就break退出 |
| 386 | imgNum := len(files) |
| 387 | var validFile string |
| 388 | for i := 0; i < len(files) && i < 10; i++ { |
| 389 | imgFile := files[rand.Intn(imgNum)] |
| 390 | if !imgFile.IsDir() && strings.HasSuffix(imgFile.Name(), ".png") && !strings.HasSuffix(imgFile.Name(), "signin.png") { |
| 391 | validFile = imgFile.Name() |
| 392 | break |
| 393 | } |
| 394 | } |
| 395 | if len(validFile) == 0 { |
| 396 | return errors.New("copyImage: no local image") |
| 397 | } |
| 398 | selectedFile := cachePath + validFile |
| 399 | |
| 400 | // 使用 io.Copy 复制签到背景 |
| 401 | srcFile, err := os.Open(selectedFile) |
| 402 | if err != nil { |
| 403 | return err |
| 404 | } |
| 405 | defer srcFile.Close() |
| 406 | |
| 407 | dstFile, err := os.Create(picFile) |
| 408 | if err != nil { |
| 409 | return err |
| 410 | } |
| 411 | defer dstFile.Close() |
| 412 | _, err = io.Copy(dstFile, srcFile) |
| 413 | if err != nil { |
| 414 | return err |
| 415 | } |
| 416 | |
| 417 | return err |
| 418 | } |