Skip to content

imura81gt: 課題1 #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
183 changes: 183 additions & 0 deletions kadai1/imura81gt/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
Convert Image
================================================================================

TOC
--------------------------------------------------------------------------------
- [Convert Image](#convert-image)
- [TOC](#toc)
- [Q. 【TRY】画像変換コマンドを作ろう](#q-try画像変換コマンドを作ろう)
- [Links](#links)
- [About filepath](#about-filepath)
- [About image](#about-image)
- [Build](#build)
- [Usage](#usage)
- [Test Data](#test-data)
- [Example](#example)
- [e.g. use no option](#eg-use-no-option)
- [e.g. use option](#eg-use-option)

Q. 【TRY】画像変換コマンドを作ろう
--------------------------------------------------------------------------------

次の仕様を満たすコマンドを作って下さい

- [x] 1. ディレクトリを指定する
- [x] 2. 指定したディレクトリ以下のJPGファイルをPNGに変換(デフォルト)
- [x] 3. ディレクトリ以下は再帰的に処理する
- [x] 4. 変換前と変換後の画像形式を指定できる(オプション)

以下を満たすように開発してください

- [x] 5. mainパッケージと分離する
- [x] 6. 自作パッケージと標準パッケージと準標準パッケージのみ使う
- 準標準パッケージ:golang.org/x以下のパッケージ
- [x] 8. ユーザ定義型を作ってみる
- [x] 9. GoDocを生成してみる


Links
--------------------------------------------------------------------------------

### About filepath

- https://golang.org/pkg/path/filepath/

### About image

- [Package image](https://golang.org/pkg/image/)
- [gif](https://golang.org/pkg/image/gif/)
- [jpeg](https://golang.org/pkg/image/jpeg/)
- [png](https://golang.org/pkg/image/png/)
- get format
- [DecodeConfig](https://golang.org/pkg/image/#DecodeConfig)
- [The Go Blog](https://blog.golang.org/)
- [The Go image package](https://blog.golang.org/go-image-package#TOC_5.)


Go doc
--------------------------------------------------------------------------------

```
$ go doc github.com/gopherdojo/dojo7/kadai1/imura81gt/imgconv/img
package img // import "github.com/gopherdojo/dojo7/kadai1/imura81gt/imgconv/img"

func AllImageFiles(dirs []string) (files []string)
func Convert(r io.Reader, w io.Writer, t string) error
func ConvertAll(dirs []string, iType ImageType, oType ImageType) error
func ExpectedImageFiles(files []string, iType ImageType) (f []string)
func IsExpectedImage(path string, iType ImageType) bool
func IsImage(path string) bool
type ImageType struct{ ... }
```

OR

```
cd $(go env GOPATH)/src/github.com/gopherdojo/dojo7/kadai1/imura81gt/imgconv
godoc -http=:8080
```

http://localhost:8080/pkg/github.com/gopherdojo/dojo7/kadai1/imura81gt/imgconv/img/

Build
--------------------------------------------------------------------------------

```
cd $(go env GOPATH)/src/github.com/gopherdojo/dojo7/kadai1/imura81gt/imgconv
GO111MODULE=on go build
```

Usage
--------------------------------------------------------------------------------

```
$ ./imgconv
./imgconv <option> dir1 dir2 dir3
option:
-G convert to gif.
-J convert to jpeg.
-P convert to png.
-g inpt files are gif.
-j inpt files are jpeg.
-p inpt files are png.
```


Test Data
--------------------------------------------------------------------------------

```
$ tree testdata/
testdata/
├── chdir
│ ├── gLenna.gif
│ ├── jLenna.jpeg
│ └── pLenna.png
├── gLenna.gif
├── jLenna.jpg
├── pLenna.png
├── this_is_not_image.gif
├── this_is_not_image.jpg
└── this_is_not_image.png

1 directory, 9 files
$
```


Example
--------------------------------------------------------------------------------

### e.g. use no option

```
$ ./imgconv testdata/
```

In stdout, the command output input files and output files.

```
["testdata/chdir/jLenna.jpeg" "testdata/jLenna.jpg"]
["output/png/testdata/chdir/jLenna.png" "output/png/testdata/jLenna.png"]
```

```
$ tree output/
output/
└── png
└── testdata
├── chdir
│ └── jLenna.png
└── jLenna.png
$
```

### e.g. use option

- input: png, jpeg
- output: gif

```
$ ./imgconv testdata/ -p -j -G
```

In stdout, the command output input files and output files.

```

["testdata/chdir/jLenna.jpeg" "testdata/chdir/pLenna.png" "testdata/jLenna.jpg" "testdata/pLenna.png"]
["output/gif/testdata/chdir/jLenna.gif" "output/gif/testdata/chdir/pLenna.gif" "output/gif/testdata/jLenna.gif" "output/gif/testdata/pLenna.gif"]
```

```
$ tree output/
output/
└── gif
└── testdata
├── chdir
│ ├── jLenna.gif
│ └── pLenna.gif
├── jLenna.gif
└── pLenna.gif
$
```
2 changes: 2 additions & 0 deletions kadai1/imura81gt/imgconv/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
output
imgconv
3 changes: 3 additions & 0 deletions kadai1/imura81gt/imgconv/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/gopherdojo/dojo7/kadai1/imura81gt/imgconv

go 1.12
1 change: 1 addition & 0 deletions kadai1/imura81gt/imgconv/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
github.com/gopherdojo/dojo7 v0.0.0-20190903074013-69385d40c994 h1:UbdhtSFDdFiSYOb/TkEmlRIUFQRrBlKOzVDY3+SXaSw=
184 changes: 184 additions & 0 deletions kadai1/imura81gt/imgconv/img/convert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
package img

import (
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"os"
"path/filepath"
)

const (
saveDir = "output"
pngType = "png"
jpegType = "jpeg"
gifType = "gif"
)

// ConvType is type of converted image files
// 8. ユーザ定義型を作ってみる
type ImageType struct {
Png bool
Jpeg bool
Gif bool
}

func (i ImageType) Enable() []string {
var types []string
if i.Png {
types = append(types, pngType)
}
if i.Jpeg {
types = append(types, jpegType)
}
if i.Gif {
types = append(types, gifType)
}
return types
}

// ConvertAll convert all image files in dirs
func ConvertAll(dirs []string, iType ImageType, oType ImageType) error {
files := AllImageFiles(dirs)
files = ExpectedImageFiles(files, iType)
fmt.Printf("%q\n", files)

var oFiles []string
for _, iPath := range files {
for _, t := range oType.Enable() {
oPath := filepath.Join(saveDir, t, iPath[:len(iPath)-len(filepath.Ext(iPath))]+"."+t)

i, err := os.Open(iPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

err = os.MkdirAll(filepath.Dir(oPath), 0755)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

w, err := os.Create(oPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
Copy link
Author

@imura81gt imura81gt Sep 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[self review]

  • deferで閉じるの忘れている。。
  • 書き込み時のclose のエラー処理する


err = Convert(i, w, t)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
oFiles = append(oFiles, oPath)
}
}
fmt.Printf("%q\n", oFiles)
return nil
}

func AllImageFiles(dirs []string) (files []string) {
// 3. ディレクトリ以下は再帰的に処理する
for _, dir := range dirs {
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}

if IsImage(path) {
files = append(files, path)
}

return nil
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
return files
}

func ExpectedImageFiles(files []string, iType ImageType) (f []string) {
var ret []string
for _, path := range files {
if IsExpectedImage(path, iType) {
ret = append(ret, path)
}
}
return ret
}

// IsImage return true if path is image.
func IsImage(path string) bool {
r, err := os.Open(path)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer r.Close()

_, _, err = image.DecodeConfig(r)
if err != nil {
return false
}
return true
}

func IsExpectedImage(path string, iType ImageType) bool {
r, err := os.Open(path)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer r.Close()

_, format, err := image.DecodeConfig(r)
if err != nil {
return false
}

for _, t := range iType.Enable() {
if t == format {
return true
}
}

return false
}

// Convert function is image file converter
func Convert(r io.Reader, w io.Writer, t string) error {
jpego := &jpeg.Options{
Quality: jpeg.DefaultQuality,
}

gifo := &gif.Options{
NumColors: 256,
Quantizer: nil,
Drawer: nil,
}

m, _, err := image.Decode(r)
if err != nil {
return err
}

switch t {
case "png":
return png.Encode(w, m)
case "gif":
return gif.Encode(w, m, gifo)
case "jpeg", "jpg":
return jpeg.Encode(w, m, jpego)
default:
return png.Encode(w, m)
}

return nil

}
Loading