LoginSignup
19
18

More than 5 years have passed since last update.

go langでjpgからwebpに変換する

Last updated at Posted at 2015-01-02

概要

go langでjpg形式のファイルをwebpに変換する。

前準備

go get github.com/chai2010/image

調査内容

サンプルだと、jpgファイルからwebpファイルに変換しているのだが、ファイルを経由して処理したくはないので、go lang が提供するインタフェースで使えるかを調査した。

内容


package webp

import (
    "image"
    "io"

    ImageExt "github.com/chai2010/image"
    _ "github.com/chai2010/image/jpeg"
    _ "github.com/chai2010/image/webp"
)

type Options struct {
    Lossless bool
    Quality  float32
}

func Decode(r io.Reader) (image.Image, error) {
    m, _, err := ImageExt.Decode(r)

    if err != nil {
        return nil, err
    }

    return m, err

}

func Encode(w io.Writer, i image.Image, options *Options) error {
    return ImageExt.Encode("webp", w, i, ImageExt.NewOptions(options.Lossless, options.Quality))
}


import (
    "github.com/masayukioguni/go-webp-sample/webp"
    "os"
    "path/filepath"
)

func main() {
    f, _ := os.Open("sample.jpg")
    defer f.Close()

    m, _ := webp.Decode(f)

    toimg, _ := os.Create("new.webp")
    defer toimg.Close()

    _ = webp.Encode(toimg, m, &webp.Options{false, 50})

}

まとめ

  • LosslessやQualityには別途調べる必要がある
  • いつかgo langに実装されそうな機能なので、go langにはいったらそっちを使いたい。
  • go langは楽しい

資料

変換ライブラリ
サンプルソース

19
18
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
19
18