Asp.net-Core-2.0
如何在 ASP.NET Core 2.0 中上傳後調整圖像大小
我想調整圖像大小並將此圖像以不同大小多次保存到文件夾中。我已經嘗試過 ImageResizer 或 CoreCompat.System.Drawing 但這些庫與 .Net core 2 不兼容。我對此進行了很多搜尋,但找不到任何合適的解決方案。就像在 MVC4 中我使用的那樣:
public ActionResult Upload(HttpPostedFileBase file) { if (file != null) { var versions = new Dictionary<string, string>(); var path = Server.MapPath("~/Images/"); //Define the versions to generate versions.Add("_small", "maxwidth=600&maxheight=600&format=jpg";); versions.Add("_medium", "maxwidth=900&maxheight=900&format=jpg"); versions.Add("_large", "maxwidth=1200&maxheight=1200&format=jpg"); //Generate each version foreach (var suffix in versions.Keys) { file.InputStream.Seek(0, SeekOrigin.Begin); //Let the image builder add the correct extension based on the output file type ImageBuilder.Current.Build( new ImageJob( file.InputStream, path + file.FileName + suffix, new Instructions(versions[suffix]), false, true)); } } return RedirectToAction("Index"); }但在 Asp.Net core 2.0 中我被卡住了。我不知道如何在 .Net core 2 中實現這一點。任何人都可以幫助我。
你可以得到 nuget 包 SixLabors.ImageSharp (不要忘記勾選“包括預發布”,因為現在它們只有測試版)並像這樣使用它們的庫。他們的GitHub
using SixLabors.ImageSharp; using SixLabors.ImageSharp.Processing; // Image.Load(string path) is a shortcut for our default type. // Other pixel formats use Image.Load<TPixel>(string path)) using (Image<Rgba32> image = Image.Load("foo.jpg")) { image.Mutate(x => x .Resize(image.Width / 2, image.Height / 2) .Grayscale()); image.Save("bar.jpg"); // Automatic encoder selected based on extension. }
.NET Core 2.0 附帶 System.Drawing.Common,它是用於 .NET Core 的 System.Drawing 的官方實現。
您可以嘗試安裝 System.Drawing.Common 並檢查它是否有效,而不是 CoreCompat.System.Drawing?