Created
June 24, 2023 00:29
-
-
Save KentaGoto/0ab51e680c516284813fe590793be826 to your computer and use it in GitHub Desktop.
Goでスクショ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"image/png" | |
"io" | |
"os" | |
"path/filepath" | |
"time" | |
"github.com/kbinani/screenshot" | |
) | |
func main() { | |
// アクティブなディスプレイの数を取得します | |
n := screenshot.NumActiveDisplays() | |
// すべてのディスプレイについて | |
for i := 0; i < n; i++ { | |
// i番目のディスプレイの領域(大きさと位置)を取得します | |
bounds := screenshot.GetDisplayBounds(i) | |
// i番目のディスプレイのスクリーンショットを撮ります | |
img, err := screenshot.CaptureRect(bounds) | |
if err != nil { | |
panic(err) | |
} | |
// 現在の日時を取得します | |
now := time.Now() | |
// 日時を文字列に変換します("YYYYMMDDhhmmss"形式) | |
dateTimeStr := now.Format("20060102150405") | |
// ファイル名を作成します(日時を最初に付けます) | |
fileName := fmt.Sprintf("%s_%d_%dx%d.png", dateTimeStr, i, bounds.Dx(), bounds.Dy()) | |
file, _ := os.Create(fileName) | |
// スクリーンショットをPNG形式でファイルに書き込みます | |
png.Encode(file, img) | |
// ファイルを閉じます | |
file.Close() | |
// どのスクリーンショットを保存したかを出力します | |
fmt.Printf("Saved screen #%d: %s\n", i, fileName) | |
// Dドライブの新しいパスを作成します(Windowsを想定しています) | |
newPath := filepath.Join("D:\\", fileName) | |
// 新しいパスで新しいファイルを作成します | |
newFile, err := os.Create(newPath) | |
if err != nil { | |
// 新しいファイルが作成できなかった場合、エラー情報を出力します | |
fmt.Printf("Failed to create new file: %v\n", err) | |
continue | |
} | |
// 元のファイルを再度開きます | |
file, err = os.Open(fileName) | |
if err != nil { | |
// 元のファイルが開けなかった場合、新しいファイルを閉じてエラー情報を出力します | |
newFile.Close() | |
fmt.Printf("Failed to open original file: %v\n", err) | |
continue | |
} | |
// 元のファイルの内容を新しいファイルにコピーします | |
_, err = io.Copy(newFile, file) | |
if err != nil { | |
// コピーが失敗した場合、エラー情報を出力します | |
fmt.Printf("Failed to copy file: %v\n", err) | |
} else { | |
// コピーが成功したら、どこにファイルをコピーしたかを出力します | |
fmt.Printf("Copied file to: %s\n", newPath) | |
} | |
// 全てのファイルを閉じます | |
file.Close() | |
newFile.Close() | |
// 元のファイルを削除します | |
err = os.Remove(fileName) | |
if err != nil { | |
// 元のファイルが削除できなかった場合、エラー情報を出力します | |
fmt.Printf("Failed to remove original file: %v\n", err) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment