Open2

【note】goで画像操作周り

not75743not75743

【image】postされた画像のサイズを返却する

  • postリクエストした画像のサイズ情報を出力する
  • jpg/pngのみ対応
  • それ以外はformatエラーを返却する
コード
main.go
package main

import (
	"fmt"
	"image"
	_ "image/jpeg" // JPEGデコーダを登録
	_ "image/png"  // PNGデコーダを登録
	"log"
	"net/http"
)

func main() {
	// /uploadエンドポイントにハンドラを登録
	http.HandleFunc("/upload", handleImageUpload)

	// サーバーを起動(ポート8080)
	fmt.Println("サーバーを開始しました。http://localhost:8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func handleImageUpload(w http.ResponseWriter, r *http.Request) {
	// POSTメソッド以外は拒否
	if r.Method != http.MethodPost {
		http.Error(w, "POSTメソッドのみ対応しています", http.StatusMethodNotAllowed)
		return
	}

	// リクエストから画像を読み込み
	file, _, err := r.FormFile("image")
	if err != nil {
		http.Error(w, "画像の読み込みに失敗しました: "+err.Error(), http.StatusBadRequest)
		return
	}
	defer file.Close()

	// 画像をデコード
	img, format, err := image.Decode(file)
	if err != nil {
		http.Error(w, "画像のデコードに失敗しました: "+err.Error(), http.StatusBadRequest)
		return
	}

	// 画像のサイズを取得
	bounds := img.Bounds()
	width := bounds.Max.X - bounds.Min.X
	height := bounds.Max.Y - bounds.Min.Y

	// レスポンスを返す(最後に改行を追加)
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"width": %d, "height": %d, "format": "%s"}`+"\n", width, height, format)
}
# 成功
$ curl -X POST -F "image=@./test.png" http://localhost:8080/upload
{"width": 160, "height": 160, "format": "png"}

$ curl -X POST -F "image=@./test.jpg" http://localhost:8080/upload
{"width": 256, "height": 256, "format": "jpeg"}

# gifを投げてフォーマット不明エラー
$ curl -X POST -F "image=@./test.gif" http://localhost:8080/upload
画像のデコードに失敗しました: image: unknown format