我需要从原始图像创建缩略图图像,并需要将这两个图像保存在本地文件夹中。我使用html文件控件上传图像
<input type="file" class="form-control" asp-for="ImageName" name="ProductImage" id="ProductImage">
到表单提交时,我将它作为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();
}
}
}
我已将其转换为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;
}
}
但我创建的方法是接受一种Image
这里有点困惑,不知道我们怎么能用byte[]
做到这一点。另外,我没有从IFileForm
获取图像本地路径,所以我不能直接给出路径。
有人可以帮我解决这个问题吗?
终于得到了答案
安装System.Drawing.Common -Version 4.5.1
包
打开包管理器并运行以下代码以安装包
Install-Package System.Drawing.Common -Version 4.5.1
Then use the below code
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;
}
}