首页 > 解决方案 > 调整 HttpFile 类型的图像大小

问题描述

我正在尝试使用 C# 中的 API 将图像上传到服务器,但在上传之前,我希望调整图像的大小。下面是我用来上传图像而不调整大小的代码。

private dynamic UploadImage(dynamic parameters)
{
    var files = Request.Files;        
    var isProfilePic = Request.Form["IsProfileImage"].Value;
    string virImgpath = string.Empty;

    if (files.Count() > 0)
    {
        HttpFile file = files.FirstOrDefault();
        string _imgname = string.Empty;

        if (file.Value != null)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                //code to upload
            }

            _userRepository.SaveImage(CurrentUser.Id, (isProfilePic == "true"), _imgname); // virImgpath
            if (isProfilePic == "true")
            {
                CurrentUser.ProfileImage = virImgpath;
            }
            else
            {
                CurrentUser.BackgroundImage = virImgpath;
            }
        }
    }

    return Response.AsJson(virImgpath);
}

现在,我正在尝试通过添加以下代码来实现调整大小的功能。

WebImage img = files.FirstOrDefault();
img.Resize(1000, 1000);
files = (IEnumerable<HttpFile>)img;

问题是文件属于该HttpFile类型,并且该Resize方法需要该WebImage类型的对象。

标签: c#asp.net-mvc

解决方案


WebImage您可以通过使用构造函数传入流来创建一个新的

var webImage = new WebImage(file.InputStream);

webImage.Resize(...,...,...,...);

https://msdn.microsoft.com/en-us/library/gg537958(v=vs.111).aspx


推荐阅读