ImageSharpを利用するコードはこちらの記事を参照してください。
Install-Package ImageProcessor -Version 2.9.1
Install-Package ImageProcessor.Plugins.WebP -Version 1.3.0
Install-Package System.Drawing.Common -Version 5.0.2
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);
});
});
}
}
}
using System.IO;
using ImageProcessor;
using ImageProcessor.Plugins.WebP.Imaging.Formats;
context.Response.ContentType = "image/webp";
FileStream fs = new FileStream("image.png", FileMode.Open);
ImageFactory imgfactory = new ImageFactory();
imgfactory.Load(fs);
fs.Close();
ImageProcessor.Plugins.WebP.Imaging.Formats.WebPFormat
オブジェクトのインスタンスを与えます。 imgfactory.Format(new WebPFormat());
MemoryStream ms = new MemoryStream();
imgfactory.Save(ms);
context.Response.Body.WriteAsync()
メソッドを呼び出し、WebP形式の画像データが書き込まれた、バイト配列をレスポンスデータとして返します。 ms.Seek(0, SeekOrigin.Begin);
byte[] imageBytes = ms.ToArray();
ms.Close();
await context.Response.Body.WriteAsync(imageBytes);
(アプリケーションルート)
のURLにアクセスします。WebP形式の画像が表示されます。