画像をWebP形式に変換する (ImageProcessor を利用) - ASP.NET Core

.NET Core アプリケーションで画像をWebP形式に変換するコードを紹介します。

概要

C# (.NET 5.0)で画像をWebP形式に変換するコードを紹介します。
画像の変換には、ImageProcessor ライブラリ(https://www.nuget.org/packages/ImageProcessor/)を利用します。
メモ
ImageSharpを利用するコードはこちらの記事を参照してください。

事前準備

.NET Core のプロジェクトを作成します。今回は、ASP.NET Core のWebアプリケーションのプロジェクトを作成します。

ImageProcessor のインストール

NuGet パッケージマネージャーコンソールで、下記のコマンドを実行して、ImageProcessor パッケージをインストールします。
Install-Package ImageProcessor -Version 2.9.1


ImageProcessor.Plugins.WebP のインストール

NuGet パッケージマネージャーコンソールで、下記のコマンドを実行して、ImageProcessor.Plugins.WebP パッケージをインストールします。
Install-Package ImageProcessor.Plugins.WebP -Version 1.3.0


System.Drawing.Common のインストール

ソリューションエクスプローラーの[NuGet パッケージの管理]を利用するか、 NuGet パッケージマネージャーコンソールで、下記のコマンドを実行して、System.Drawing.Common パッケージをインストールします。
Install-Package System.Drawing.Common -Version 5.0.2

プログラム実装

コード

ASP.NET Core アプリケーションの Startup.cs ファイルに下記のコードを記述します。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using ImageProcessor;
using ImageProcessor.Plugins.WebP.Imaging.Formats;

namespace WebPDemo
{
  public class Startup
  {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapGet("/", async context =>
              {
                context.Response.ContentType = "image/webp";
                FileStream fs = new FileStream("image.png", FileMode.Open);
                ImageFactory imgfactory = new ImageFactory();
                imgfactory.Load(fs);
                fs.Close();

                imgfactory.Format(new WebPFormat());
                MemoryStream ms = new MemoryStream();
                imgfactory.Save(ms);

                ms.Seek(0, SeekOrigin.Begin);
                byte[] imageBytes = ms.ToArray();
                ms.Close();
                await context.Response.Body.WriteAsync(imageBytes);
              });
      });
    }
  }
}

解説

System.IO と ImageProcessor, ImageProcessor.Plugins.WebP.Imaging.Formats の参照を追加します。
using System.IO;
using ImageProcessor;
using ImageProcessor.Plugins.WebP.Imaging.Formats;

MapGetメソッドでは、アプリケーションルートにアクセスすると、WebP形式の画像を返すロジックを実装します。
WebP画像をレスポンスとして返すため、レスポンスのContentTypeに "image/webp" を指定します。
  context.Response.ContentType = "image/webp";

FileStream オブジェクトを作成し元画像のPNGファイルを開きます。
FileStreamの作成後、ImageFactory オブジェクトを作成します。ImageFactoryオブジェクトのLoadメソッドを呼び出し、 元画像のデータを読み込みます。Loadメソッドの引数にFileStreamオブジェクトを与えます。
画像の読み込みができたら、FileStreamオブジェクトは Close() メソッドを呼び出しファイルを閉じます。
  FileStream fs = new FileStream("image.png", FileMode.Open);
  ImageFactory imgfactory = new ImageFactory();
  imgfactory.Load(fs);
  fs.Close();

ImageFactory オブジェクトの Format メソッドを呼び出し、変換先の画像形式を設定します。 画像形式はFormatメソッドの引数に ImageProcessor.Plugins.WebP.Imaging.Formats.WebPFormat オブジェクトのインスタンスを与えます。
変換後の画像を保存するMemoryStreamを作成します。ImageFactoryオブジェクトのSave メソッドを呼び出し、作成したMemoryStreamに変換後の画像を書き込みます。
  imgfactory.Format(new WebPFormat());
  MemoryStream ms = new MemoryStream();
  imgfactory.Save(ms);

Seekメソッドを呼び出し、MemoryStream の位置を先頭に戻します。
MemoryStreamオブジェクトの ToArray() メソッドを呼び出し、MemoryStreamの内容をバイト配列に変換します。 バイト配列に設定ができたらMemoryStramは使わないため、ストリームは閉じます。
context.Response.Body.WriteAsync() メソッドを呼び出し、WebP形式の画像データが書き込まれた、バイト配列をレスポンスデータとして返します。
  ms.Seek(0, SeekOrigin.Begin);
  byte[] imageBytes = ms.ToArray();
  ms.Close();
  await context.Response.Body.WriteAsync(imageBytes);

画像

画像ファイルは下図を用意します。

ソリューションエクスプローラー

ファイルの配置は下図の通りです。

実行結果

プロジェクトを実行します。(アプリケーションルート) のURLにアクセスします。WebP形式の画像が表示されます。


画像を保存します。".webp" 拡張子で保存されます。


元のファイルとサイズを比較してみます。ダウンロードしたファイルはWebP形式のため、元のPNGファイルよりサイズが小さくなっていることが確認できます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2023-07-31
作成日: 2021-05-10
iPentec all rights reserverd.