LoginSignup
2
3

More than 3 years have passed since last update.

golangの画像処理まわり

Posted at

Composite

image/drawのDrawを使う。
マスクをかけるときはDrawMask。

Scale

golang.org/x/image/drawを使う。image/drawのスーパーセットになっている。
Scale用にScalerというinterfaceが定義されていて、BiLinearとかCatmullRomとかいくつかアルゴリズムが提供されている。

func (*Kernel) Scale でscaleする。

pngとかjpeg

image/pngimage/jpegのDecode, Encodeを使う。
以下のようにimage/pngimage/jpegをblank importしておくと画像フォーマットをよしなにデコードしてくれる。

import (
    "image"
    _ "image/jpeg"
    _ "image/png"
)

func decode(src io.Reader) {
    im, t, err := image.Decode(src)
}

pixel値取得

image.Image interfaceのAtを使う。

r, g, b ,a := im.At(x, y).RGBA()

pixel値設定

image.RGBA 等はSetメソッドがあるのでこれでpixel値を設定できる。
image.Image interfaceにはSetがないのでpng.Decode等で得たあとは

type Setter interface {
    Set(x, y int, c color.Color)
}

if sim, ok := im.(Setter); ok {
    // ...
}

というようにinterface定義して型アサーションをかける。

Crop

image.RGBA 等はSubImageメソッドがあるのでこれでCropできる。
image.Image interfaceにはSubImageがないのでpng.Decode等で得たあとは

type SubImager interface {
    SubImage(r image.Rectangle) image.Image
}

if sim, ok := im.(SubImager); ok {
    // ...
}

というようにinterface定義して型アサーションをかける。

2
3
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
2
3