【问题标题】:Getting image format in C# [duplicate]在 C# 中获取图像格式 [重复]
【发布时间】:2016-06-26 16:18:58
【问题描述】:

我已经写了这段代码。我想在 asp.net C# 程序中上传 2 张图片(图片和 Gif)。我接受 JPG 格式的图像。

你能告诉我怎么做吗?

我阅读了所有与我的问题相似的主题!请不要把我介绍给他们!:)

public ActionResult Upload(HttpPostedFileBase image , HttpPostedFileBase Gif)
{
    Image i = Image.FromFile("image.FileName");

    if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(i.RawFormat))
    {
        string imageName = Path.GetFileName(image.FileName);
        string image_path = Server.MapPath("~/Images/" + imageName);
        image.SaveAs(image_path);

        ViewBag.image_path = image_path;
    }

    string gifName = Path.GetFileName(Gif.FileName);
    string gif_path = Server.MapPath("~/Images/" + gifName);
    Gif.SaveAs(gif_path);

    ViewBag.gif_path = gif_path;

    return View();
}

【问题讨论】:

  • 我有 2 个文件。一张 JPG 格式的图片和另一张 Gif 格式的图片。我不写关于 Gif 条件的那部分@marc_s

标签: c# asp.net


【解决方案1】:

为此目的使用Path.GetExtension(); 方法。喜欢

if(Path.GetExtension(image.FileName) == ".jpg")
{
  //do your work
}

修改你的代码有点像

if (image != null && Path.GetExtension(image.FileName).ToLower() == ".jpeg") 
{ 
   string imageName = Path.GetFileName(image.FileName); 
   string image_path = Path.Combine(Server.MapPath("~/Images/"), imageName); 
   image.SaveAs(image_path); 
   ViewBag.image_path = image_path; 
}

【讨论】:

  • 我把我的代码改成了这个,但我的问题没有解决。我的文件没有上传到图片文件夹if (Path.GetExtension(image.FileName) == ".jpg") { string imageName = Path.GetFileName(image.FileName); string image_path = Server.MapPath("~/Images/" + imageName); image.SaveAs(image_path); ViewBag.image_path = image_path; }@Rahul
  • 如果有帮助,请查看答案中的编辑。
  • 谢谢!很好的答案,但是当我调试它时,“imageName”为空!并且不允许程序将我的文件保存在图像文件夹@Rahul
  • 发布您的呼叫代码。想看看你在传递什么。
  • @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })){ <p>Name: @Html.TextBoxFor(x => x.Name) </p> <p>Image:</p><input type="file" name="image" id="image"/> <p>Gif:</p><input type="file" name="Gif" id="Gif" /> <input type="submit" value="Upload" /> }
猜你喜欢
  • 2014-04-30
  • 1970-01-01
  • 2017-06-03
  • 2016-03-28
  • 2017-04-06
  • 1970-01-01
  • 2012-07-10
  • 2016-03-26
  • 2018-07-11
相关资源
最近更新 更多