0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GoでバイナリからJPEG生成

Last updated at Posted at 2020-08-11

Goでバイナリでファイルを受け取った際にそのまま加工したい時

結論
bytes パッケージを使おう
Go言語 パッケージ bytes

ソースコード

main.go

package main

import (
	"bytes"
	"fmt"
	"image"
	"image/jpeg"
	"io/ioutil"
	"os"
)

func main() {

    // ファイルの読み込み
	buf, _ := ioutil.ReadFile("input.jpg")

    // バイナリファイルをReaderに読み込み
	reader := bytes.NewReader(buf)

    // 画像変換
	img, _, err := image.Decode(reader)
	if err != nil {
		fmt.Errorf("err %v", err)
	}

    // ファイル作成
	f, err := os.Create("output.jpg")
	if err != nil {
		fmt.Errorf("err %v", err)
	}
	defer f.Close()

	opt := jpeg.Options{
		Quality: 90,
	}

    // 今回はJPEGだがPNGとかでもできそう
	if err = jpeg.Encode(f, img, &opt); err != nil {
		fmt.Errorf("err %v", err)
	}
}


参考

Go言語 パッケージ bytes Reader

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?