Skip to content

Instantly share code, notes, and snippets.

@shiimaxx
Created April 25, 2018 11:52
Show Gist options
  • Save shiimaxx/2bfa07c6572fe29f0ab141563bf651d8 to your computer and use it in GitHub Desktop.
Save shiimaxx/2bfa07c6572fe29f0ab141563bf651d8 to your computer and use it in GitHub Desktop.
`jpeg.Encode`のコードリーディング
func Encode(w io.Writer, m image.Image, o *Options) error {

引数wio.Writerインターフェースを実装している型の変数を取る。

	var e encoder
	if ww, ok := w.(writer); ok {
		e.w = ww
	} else {
		e.w = bufio.NewWriter(w)
	}

jepg.writerインターフェースに変換。
キャストできればそのまま。できない場合はbufio.NewWrite()で行う。

type writer interface {
	Flush() error
	io.Writer
	io.ByteWriter
}

jpeg.writerインターフェースの定義。
bufio.NewWriter()bufio.Writerを返す。これはjpeg.writerインターフェースを実装している。

	// Write the Start Of Image marker.
	e.buf[0] = 0xff
	e.buf[1] = 0xd8
	e.write(e.buf[:2])
	// Write the quantization tables.
	e.writeDQT()
	// Write the image dimensions.
	e.writeSOF0(b.Size(), nComponent)
	// Write the Huffman tables.
	e.writeDHT(nComponent)
	// Write the image data.
	e.writeSOS(m)
	// Write the End Of Image marker.
	e.buf[0] = 0xff
	e.buf[1] = 0xd9
	e.write(e.buf[:2])
	e.flush()

このあたりで変換後の書き込みをしていると思われる。
いずれの処理も内部的にjpeg.writerインターフェースのメソッドを利用している。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment