代码之家  ›  专栏  ›  技术社区  ›  dtc

如何从ASP.NET中的文件上载控件创建图像对象?

  •  0
  • dtc  · 技术社区  · 15 年前

    我有一个文件上传控件。我正在尝试保存上载的文件(图像),并保存该文件的几个缩略图副本。

    当我尝试这样的方法时:

    system.drawing.image imgoriginal=system.drawing.image.fromstream(photoupload.postedfile.inputstream);

    我得到一个“System.ArgumentException:参数无效。”

    我还尝试使用photoupload.file bytes从文件字节(而不是inputstream)创建图像,但发生了相同的错误。

    上载的文件是JPG。我知道这是一个有效的JPG,因为它保存了原始的OK。

    编辑:这个代码确实有效。参数无效,因为photoupload.postedfile.inputstream为空…这似乎是一个完全不同的问题。在我保存原始文件之后,文件上传流就消失了。

    编辑:发现文件上传的输入流只能读取/使用一次,然后就消失了。

    为了解决这个问题,我将fileupload filebytes保存到一个字节数组中,并使用字节数组创建图像的副本。

    代码:

    // Copy the FileBytes into a byte array
    byte[] imageData = PhotoUpload.FileBytes;
    
    // Create a stream from the byte array if you want to save it somewhere:
    System.IO.Stream myStream = new System.IO.MemoryStream(imageData);
    
    // Or create an image from the stream as many times as needed:
    System.Drawing.Image imgOriginal = System.Drawing.Image.FromStream(myStream);
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   Adriaan Stander    15 年前

    看看这个链接

    ASP Net - How to pass a postedfile to a system.drawing.image

    这是我的函数调用:

    上载和大小图像(system.drawing.image.fromstream (uploadedfilemd.postedfile.inputstream)

    我得到这个错误:

    异常详细信息: System.ArgumentException:无效 使用的参数。

    虽然我的谷歌没有出现太多 可能找到了一个参考 由流读取器引起 在小溪的尽头和我 需要将其重置到位置1。 但那有点含糊 真的确定它是否适用于这里。

    这有帮助吗?

    编辑:

    另外,您是否尝试使用类似

    System.IO.FileStream fs = System.IO.File.OpenRead(@"Image.JPG");
    byte[] data = new byte[fs.Length];
    fs.Read(data, 0, data.Length);
    
    System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
    System.Drawing.Image image = Image.FromStream(ms);
    

    还是从文件中保存临时副本上载并从文件中加载图像?

    推荐文章