是否可以将单个System.Web.HttpPostedFileBase图像(任何类型)转换为位图对象



好的,正如标题所暗示的那样,我正在尝试将单个System.Web.HttpPostedFileBase发布的图像(任何类型的)转换为位图对象。我基本上需要这样做才能在保存文件后关闭对象。

这是我到目前为止的代码:

var PortraitImage = Request.Files["PortraitImageSelector"];
string FileName = Guid.NewGuid().ToString() + Path.GetExtension(PortraitImage.FileName);
string PortraitImageFullLocation = Path.Combine(Server.MapPath(_VirtualPath), FileName);
string PortraitImageURL = string.Format("{0}/{1}", _VirtualPath, FileName);
using (var bmp = new Bitmap(PortraitImageFullLocation))
{
    bmp.Save(PortraitImageFullLocation);
}

不幸的是,当我运行它时,我收到一个异常,指出以下内容:

{"Parameter is not valid."}
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2147024809
    HelpLink: null
    InnerException: null
    Message: "Parameter is not valid."
    ParamName: null
    Source: "System.Drawing"
    StackTrace: "   at System.Drawing.Bitmap..ctor(String filename)rn   at johneschultz.Areas.Admin.Controllers.EmployeeController.Edit(EmployeeViewModel EmployeeData) in Z:\_Profile Storage\Projects\johneschultz\johneschultz\Areas\Admin\Controllers\EmployeeController.cs:line 552"
    TargetSite: {Void .ctor(System.String)}

要将HttpPostedFileBase保存为BitMap,只需使用InputStream,因为BitMap有一个接受Stream的构造函数:

using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(this.Request.Files[0].InputStream))
{
    bmp.Save("whatever.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
}

最新更新