LoginSignup
0
1

More than 3 years have passed since last update.

C#にpngoutを組み込んでPNGファイルを無劣化で高圧縮

Last updated at Posted at 2019-09-24

pngoutとは

Ken Silvermanさんが開発したpng画像を無劣化圧縮するWindowsソフト.
optipngより処理時間は長いが圧縮後のファイルサイズは小さい.筆者の環境ではpngquantは確率2-3 %でファイルが破壊される.よってpngoutが優れていると言える.
GUI版は試用期間のあるシェアウエア.
CUI版は有り難いことにフリーソフトになっている.
商用利用は
http://advsys.net/ken/utils.htm#pngoutkziplicense
によるとDavid Blakeさんに確認してくれとのこと.

pngout.exeの入手

実行ファイルのあるところにpngout.exeを配置する必要がある.(パスの通っている場所でもいい)
以下からCUI版をダウンロードする.
http://advsys.net/ken/util/pngout.exe

高速化

並列化されていないので処理時間が非常に長い(1枚当たり数分レベル).
故にファイル毎に並列化して誤魔化す.

プログラムの説明

ExecutePNGout(...)pngout.exeを呼び出すための引数を作る
in string PathName//pngファイルが入っているフォルダ. ※pngファイルではない.
IEnumerable PNGFiles //フォルダ内のpngファイル群
MaxDegreeOfParallelism//最大並列数
System.Environment.ProcessorCount//コンピュータの論理プロセッサの数を取得(4 cores 8 threadsなら8).
ExecuteAnotherApp(...)//pngout.exeの呼び出し元

ExecutePNGout.cs
using System.Threading.Tasks;//setparalle
using System.Linq;
using System.Collections.Generic;
    public static void ExecutePNGout(in string PathName){
        IEnumerable<string> PNGFiles = System.IO.Directory.EnumerateFiles(PathName, "*.png", System.IO.SearchOption.AllDirectories);//Acquire only png files under the path.
        if (PNGFiles.Any()) {//pngファイルがあるか
            Parallel.ForEach(PNGFiles, new ParallelOptions() { MaxDegreeOfParallelism = System.Environment.ProcessorCount }, f => {
                ExecuteAnotherApp("pngout.exe", "\"" + f + "\"", false, true);//PNGOptimize
            });
        }
    }
    public static void ExecuteAnotherApp(in string FileName, in string Arguments, bool UseShellExecute, bool CreateNoWindow){//外部アプリの呼び出し
        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo {
            FileName = FileName,
            Arguments = Arguments,
            UseShellExecute = UseShellExecute,
            CreateNoWindow = CreateNoWindow    // コンソール・ウィンドウを開かない
        }).WaitForExit();
    }

非常に処理が遅いのでasync awaitを使ってGUIのフリーズを抑えたほうがいいと思います.
async await の使い方

0
1
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
0
1