diff --git a/kadai1/hiroygo/.gitignore b/kadai1/hiroygo/.gitignore new file mode 100644 index 0000000..39a03ac --- /dev/null +++ b/kadai1/hiroygo/.gitignore @@ -0,0 +1,354 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# add +*.o +.vscode/ \ No newline at end of file diff --git a/kadai1/hiroygo/README.md b/kadai1/hiroygo/README.md new file mode 100644 index 0000000..ac6ce9c --- /dev/null +++ b/kadai1/hiroygo/README.md @@ -0,0 +1,41 @@ +# 課題1 +## 【TRY】画像変換コマンドを作ろう +### 次の仕様を満たすコマンドを作って下さい +* ディレクトリを指定する +* 指定したディレクトリ以下のJPGファイルをPNGに変換(デフォルト) +* ディレクトリ以下は再帰的に処理する +* 変換前と変換後の画像形式を指定できる(オプション) + +### 以下を満たすように開発してください +* mainパッケージと分離する +* 自作パッケージと標準パッケージと準標準パッケージのみ使う + * 準標準パッケージ:golang.org/x以下のパッケージ +* ユーザ定義型を作ってみる +* GoDocを生成してみる +* Go Modulesを使ってみる + +## 使用方法 +* jpg, png, tiff, bmp, gif に対応しています + +``` +$ ./imgcnv -h +Usage of ./imgcnv: + -d string + 変換の対象となる画像が格納されたディレクトリパス (default "./") + -i string + 変換の対象となる画像種別 (default "jpg") + -o string + 変換後の画像種別 (default "png") +``` + +## 実行例 +* 以下は testdata ディレクトリ内の tiff 画像を bmp 画像に変換して出力します + +``` +$ ./imgcnv -d testdata -i tiff -o bmp +``` + +## 感想 +* 画像変換は C++ と Windows Imaging Component の組み合わせで実装したことがありました。 +* この時は低レイヤーな関数を扱わなくてはいけなくて、苦労しました。 +* Go では抽象化された関数などが用意されていて、簡単に画像変換できました。 \ No newline at end of file diff --git a/kadai1/hiroygo/go.mod b/kadai1/hiroygo/go.mod new file mode 100644 index 0000000..d19da9a --- /dev/null +++ b/kadai1/hiroygo/go.mod @@ -0,0 +1,5 @@ +module github.com/gopherdojo/dojo8/kadai1/hiroygo + +go 1.14 + +require golang.org/x/image v0.0.0-20200618115811-c13761719519 diff --git a/kadai1/hiroygo/go.sum b/kadai1/hiroygo/go.sum new file mode 100644 index 0000000..394251b --- /dev/null +++ b/kadai1/hiroygo/go.sum @@ -0,0 +1,3 @@ +golang.org/x/image v0.0.0-20200618115811-c13761719519 h1:1e2ufUJNM3lCHEY5jIgac/7UTjd6cgJNdatjPdFWf34= +golang.org/x/image v0.0.0-20200618115811-c13761719519/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= diff --git a/kadai1/hiroygo/imgconv/imgconv.go b/kadai1/hiroygo/imgconv/imgconv.go new file mode 100644 index 0000000..a03b241 --- /dev/null +++ b/kadai1/hiroygo/imgconv/imgconv.go @@ -0,0 +1,161 @@ +package imgconv + +import ( + "errors" + "fmt" + "image" + "image/gif" + "image/jpeg" + "image/png" + "os" + "path/filepath" + "strings" + + "golang.org/x/image/bmp" + "golang.org/x/image/tiff" +) + +const ( + // Unknown 不明な画像 + Unknown ImageType = "unknown" + // Jpeg Jpeg 画像 + Jpeg ImageType = "jpg" + // Png Png 画像 + Png ImageType = "png" + // Tiff Tiff 画像 + Tiff ImageType = "tiff" + // Bmp Bmp 画像 + Bmp ImageType = "bmp" + // Gif Gif 画像 + Gif ImageType = "gif" +) + +// ImageType 画像種別 +type ImageType string + +func (t ImageType) String() string { + return string(t) +} + +// ToImageType 文字列を ImageType に変換する +// e.g. "jpg" => Jpeg +func ToImageType(s string) ImageType { + switch s { + case "jpeg", "jpg": + return Jpeg + case "png": + return Png + case "tiff": + return Tiff + case "bmp": + return Bmp + case "gif": + return Gif + default: + return Unknown + } +} + +func imageTypeFromFileName(name string) ImageType { + extWithoutDot := strings.TrimLeft(filepath.Ext(name), ".") + return ToImageType(strings.ToLower(extWithoutDot)) +} + +// ImageFilePathesRecursive ディレクトリ内の指定された画像種別のファイルパスを再帰的に返す +func ImageFilePathesRecursive(dir string, target ImageType) ([]string, error) { + var pathes []string + err := filepath.Walk(dir, func(visitPath string, f os.FileInfo, err error) error { + if err != nil { + return fmt.Errorf("WalkFunc error, %w", err) + } + + if !f.Mode().IsRegular() { + return nil + } + + t := imageTypeFromFileName(f.Name()) + if t != target { + return nil + } + + pathes = append(pathes, visitPath) + return nil + }) + if err != nil { + return nil, fmt.Errorf("Walk error, %w", err) + } + + return pathes, nil +} + +// LoadImage 画像を読み込み、その Image を返す +func LoadImage(path string) (image.Image, error) { + f, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("Open error, %w", err) + } + defer f.Close() + + m, _, err := image.Decode(f) + if err != nil { + return nil, fmt.Errorf("Decode error, %w", err) + } + + return m, nil +} + +// ReplaceExt 画像ファイルパスの拡張子を置換した結果を返す +func ReplaceExt(path string, replace ImageType) string { + newName := filepath.Base(path[:len(path)-len(filepath.Ext(path))]) + newName += "." + replace.String() + return filepath.Join(filepath.Dir(path), newName) +} + +// SaveImage Image を指定された画像形式で保存する +func SaveImage(m image.Image, out ImageType, savePath string) (rerr error) { + if m == nil { + return errors.New("Image が nil です") + } + + var encoder func(*os.File, image.Image) error + switch out { + case Jpeg: + encoder = func(f *os.File, m image.Image) error { + return jpeg.Encode(f, m, nil) + } + case Png: + encoder = func(f *os.File, m image.Image) error { + return png.Encode(f, m) + } + case Tiff: + encoder = func(f *os.File, m image.Image) error { + return tiff.Encode(f, m, nil) + } + case Bmp: + encoder = func(f *os.File, m image.Image) error { + return bmp.Encode(f, m) + } + case Gif: + encoder = func(f *os.File, m image.Image) error { + return gif.Encode(f, m, nil) + } + default: + return fmt.Errorf("画像種別 %s は不明です", out.String()) + } + + f, err := os.Create(savePath) + if err != nil { + return fmt.Errorf("Create error, %w", err) + } + defer func() { + if err := f.Close(); err != nil { + rerr = fmt.Errorf("Close error, %w", err) + } + }() + + if err := encoder(f, m); err != nil { + return fmt.Errorf("Encode error, %w", err) + } + + return +} diff --git a/kadai1/hiroygo/main.go b/kadai1/hiroygo/main.go new file mode 100644 index 0000000..f203fd1 --- /dev/null +++ b/kadai1/hiroygo/main.go @@ -0,0 +1,56 @@ +package main + +import ( + "flag" + "fmt" + "os" + + "github.com/gopherdojo/dojo8/kadai1/hiroygo/imgconv" +) + +func parseArgs() (dir string, in, out imgconv.ImageType, err error) { + d := flag.String("d", "./", "変換の対象となる画像が格納されたディレクトリパス") + i := flag.String("i", "jpg", "変換の対象となる画像種別") + o := flag.String("o", "png", "変換後の画像種別") + flag.Parse() + + in = imgconv.ToImageType(*i) + out = imgconv.ToImageType(*o) + if in == imgconv.Unknown || out == imgconv.Unknown { + in = imgconv.Unknown + out = imgconv.Unknown + err = fmt.Errorf("設定された画像種別が不正です") + return + } + + dir = *d + return +} + +func main() { + dir, inType, outType, err := parseArgs() + if err != nil { + fmt.Fprintln(os.Stderr, err) + return + } + + pathes, err := imgconv.ImageFilePathesRecursive(dir, inType) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return + } + + for _, path := range pathes { + m, err := imgconv.LoadImage(path) + if err != nil { + fmt.Fprintf(os.Stderr, "%s の読み込みに失敗しました。%v\n", path, err) + continue + } + + savePath := imgconv.ReplaceExt(path, outType) + if err := imgconv.SaveImage(m, outType, savePath); err != nil { + fmt.Fprintf(os.Stderr, "%s の保存に失敗しました。%v\n", savePath, err) + continue + } + } +} diff --git a/kadai1/hiroygo/testdata/go.bmp b/kadai1/hiroygo/testdata/go.bmp new file mode 100644 index 0000000..0516deb Binary files /dev/null and b/kadai1/hiroygo/testdata/go.bmp differ diff --git a/kadai1/hiroygo/testdata/go.gif b/kadai1/hiroygo/testdata/go.gif new file mode 100644 index 0000000..31350e1 Binary files /dev/null and b/kadai1/hiroygo/testdata/go.gif differ diff --git a/kadai1/hiroygo/testdata/go.jpg b/kadai1/hiroygo/testdata/go.jpg new file mode 100644 index 0000000..46ed1e0 Binary files /dev/null and b/kadai1/hiroygo/testdata/go.jpg differ diff --git a/kadai1/hiroygo/testdata/go.png b/kadai1/hiroygo/testdata/go.png new file mode 100644 index 0000000..bf47390 Binary files /dev/null and b/kadai1/hiroygo/testdata/go.png differ diff --git a/kadai1/hiroygo/testdata/go.tiff b/kadai1/hiroygo/testdata/go.tiff new file mode 100644 index 0000000..d2b3b67 Binary files /dev/null and b/kadai1/hiroygo/testdata/go.tiff differ diff --git a/kadai1/hiroygo/testdata/go_alpha.png b/kadai1/hiroygo/testdata/go_alpha.png new file mode 100644 index 0000000..138bccc Binary files /dev/null and b/kadai1/hiroygo/testdata/go_alpha.png differ diff --git a/kadai1/hiroygo/testdata/sub/go.jpg b/kadai1/hiroygo/testdata/sub/go.jpg new file mode 100644 index 0000000..46ed1e0 Binary files /dev/null and b/kadai1/hiroygo/testdata/sub/go.jpg differ