如何保存图片jpg或其他格式后,上传为png使用asp.net c#

本文关键字:png net asp 使用 格式 其他 保存 何保存 jpg | 更新日期: 2023-09-27 18:05:39

我有asp:FileUpload,我想保存所有上传的图像的所有可接受的格式为png图像在网站上的图像文件夹,我的上传代码是:

protected void btnSave_Click(object sender, EventArgs e)
    {
        if (fup2.HasFile)
        {
            Regex reg = new Regex(@"(?i).*'.(gif|jpe?g|png|tif)$");
            string uFile = fup2.FileName;
            if (reg.IsMatch(uFile))
            {
                string saveDir = Server.MapPath(@"~/Images/");
                string SavePath = saveDir + uFile;
                fup2.SaveAs(SavePath);
            }
            else
            {
                Response.Write("Error");
            }
        }
    }

我也试过使用

var tempImg = Image.FromFile(Server.MapPath(@"~/Images/")); tempImg.Save("a.tiff", ImageFormat.png);

连续抛出file not found exception

有什么新想法吗?

如何保存图片jpg或其他格式后,上传为png使用asp.net c#

使用Bitmap.FromStream。比如:

 using System.Drawing;
 protected void btnSave_Click(object sender, EventArgs e)
 {
    if (fup2.HasFile)
    {
        Regex reg = new Regex(@"(?i).*'.(gif|jpe?g|png|tif)$");
        string uFile = fup2.FileName;
        if (reg.IsMatch(uFile))
        {
            string saveDir = Server.MapPath(@"~/Images/");
            string SavePath = saveDir + Path.GetFileName(uFile) + ".png";
            Bitmap b = (Bitmap)Bitmap.FromStream(fup2.PostedFile.InputStream);
            b.Save(SavePath, ImageFormat.Png);
        }
        else
        {
            Response.Write("Error");
        }
    }
}

Image.FromFile -> Save应该做的技巧,但我不知道你是如何使用正确的路径-你只是指向目录,而不是实际的文件时调用FromFile

作为旁注,在web处理线程上进行此处理不是一个好主意,但对于小负载来说,它可以工作。