调整图像大小以存储在数据库中 - ASP.NET

Resize image to store in database - ASP.NET

我按照本指南中的代码在将图像存储到数据库之前调整图像大小: https://www.aspsnippets.com/questions/876401/Resize-image-and-save-into-Database-with-Binary-format-using-C-and-VBNet-in-ASPNet/

代码如下:

protected void Save(object sender, EventArgs e)
{
    if (fuImage.HasFile)
    {
        Byte[] bytes;
        string contentType = fuImage.PostedFile.ContentType;
        string fileName = Path.GetFileName(fuImage.FileName);
        string filePath = fuImage.PostedFile.FileName;
        System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
        // Resize image
        using (System.Drawing.Image thumbnail = image.GetThumbnailImage(130, 170, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                thumbnail.Save(memoryStream, ImageFormat.Png);
                bytes = new Byte[memoryStream.Length];
                memoryStream.Position = 0;
                memoryStream.Read(bytes, 0, (int)bytes.Length);
            }
        }
        // Insert uploaded image to Database
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = "INSERT INTO tblFiles1 VALUES (@Name, @ContentType, @Data)";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Name", fileName);
                cmd.Parameters.AddWithValue("@ContentType", contentType);
                cmd.Parameters.AddWithValue("@Data", bytes);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
    // Display image after upload to Database
    Image1.Visible = true;
    byte[] byteData = (byte[])GetData("SELECT Data FROM tblFiles1").Rows[0]["Data"];
    string base64String = Convert.ToBase64String(byteData, 0, byteData.Length);
    Image1.ImageUrl = "data:image/png;base64," + base64String;
}
 
 
public bool ThumbnailCallback()
{
    return false;
}

然而,我遇到的问题是,一旦我 select 使用 FileUploader 的图像并尝试 运行 保存方法,我在行中得到 System.IO.FileNotFoundException:

 System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);

提前致谢!

FileName 属性 是来自客户端的文件名 属性 (https://docs.microsoft.com/en-us/dotnet/api/system.web.httppostedfilebase.filename?view=netframework-4.8#System_Web_HttpPostedFileBase_FileName) so you can't load the file using that property. I can upload an image from c:\yfeyhcdrt\image.png, but this folder will probably not exist on your server. You should load it using the InputStream property instead using https://docs.microsoft.com/en-us/dotnet/api/system.drawing.image.fromstream?view=windowsdesktop-5.0