Aru*_*K V 2 c# image-processing thumbnails asp.net-core-mvc .net-core
我需要从原始图像创建缩略图,并且需要将两个图像都保存在本地文件夹中。我正在使用html文件控件上传图像
<input type="file" class="form-control" asp-for="ImageName" name="ProductImage" id="ProductImage">
Run Code Online (Sandbox Code Playgroud)
到提交表单时,我得到了 IFromFile
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Guid id, ProductDTO product, IFormFile
ProductImage)
{
if (ModelState.IsValid)
{
byte[] fileBytes;
using (var ms = new MemoryStream())
{
ProductImage.CopyTo(ms);
fileBytes = ms.ToArray();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我已将其转换为byte []并将其传递给我的一种保存方法。在这里我需要特定图像的缩略图
到目前为止,我尝试过的是添加 package Install-Package System.Drawing.Common -Version 4.5.1
并创建了一种转换图像的方法
public string ErrMessage;
public bool ThumbnailCallback()
{
return false;
}
public Image GetReducedImage(int Width, int Height, Image ResourceImage)
{
try
{
Image ReducedImage;
Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
return ReducedImage;
}
catch (Exception e)
{
ErrMessage = e.Message;
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
但是我创建的方法在这里接受的类型Image很少,因此不确定如何使用byte[]。我也没有从图像本地路径,IFileForm所以我也不能直接给出路径。
有人可以帮我解决这个问题吗?
终于得到了答案
已安装 System.Drawing.Common -Version 4.5.1套件
打开程序包管理器并运行以下代码以安装程序包
安装包System.Drawing.Common-版本4.5.1
然后使用下面的代码
Stream stream=ProductImage.OpenReadStream();
Image newImage=GetReducedImage(32,32,stream);
newImage.Save("path+filename");
public Image GetReducedImage(int width, int height, Stream resourceImage)
{
try
{
Image image = Image.FromStream(resourceImage);
Image thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero);
return thumb;
}
catch (Exception e)
{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)