如何将 HttpPostedFileBase 转换为图像?
我正在使用 ASP.NET MVC,并且有一个上传文件的操作。 文件正在正确上传。 但我想要图像的宽度和高度。 我想我需要先将 HttpPostedFileBase
转换为 Image
然后继续。 我怎么做?
请告诉我是否有其他更好的方法来获取图像的宽度和高度。
I am using ASP.NET MVC and I've an action that uploads the file. The file is being uploaded properly. But I want width and height of the image. I think I need to convert the HttpPostedFileBase
to Image
first and then proceed. How do I do that?
And please let me know if there is another better way to get the width and height of the image.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用
Image.FromStream
如下:返回的
Image
是IDisposable
。您需要引用
System.Drawing.dll
才能使其工作,并且Image
位于System.Drawing
命名空间中。调整图像大小
我不确定您要做什么,但如果您碰巧正在制作缩略图或类似的东西,您可能会对做类似的事情感兴趣...
其中
clipRectangle
是您希望缩放到新位图的原始图像的矩形(您需要手动处理宽高比)。 catch 块是构造函数内典型的 IDisposable 用法; 您保留新的IDisposable
对象的所有权,直到它返回为止(您可能需要使用代码注释来记录它)。另存为 Jpeg
不幸的是,默认的“另存为 jpeg”编码器不会公开任何质量控制,并且选择非常低的默认质量。
不过,您也可以手动选择编码器,然后可以传递任意参数:
I use
Image.FromStream
to as follows:Note that the returned
Image
isIDisposable
.You'll need a reference to
System.Drawing.dll
for this to work, andImage
is in theSystem.Drawing
namespace.Resizing the Image
I'm not sure what you're trying to do, but if you happen to be making thumbnails or something similar, you may be interested in doing something like...
where
clipRectangle
is the rectangle of the original image you wish to scale into the new bitmap (you'll need to manually deal with aspect ratio). The catch-block is typicalIDisposable
usage inside a constructor; you maintain ownership of the newIDisposable
object until it is returned (you may want to doc that with code-comments).Saving as Jpeg
Unfortunately, the default "save as jpeg" encoder doesn't expose any quality controls, and chooses a terribly low default quality.
You can manually select the encoder as well, however, and then you can pass arbitrary parameters:
如果您确定源是图像并且不需要编辑,您可以按照描述轻松完成 此处
为了确保文件是图像,请通过向输入标记
和 jQuery 验证脚本
添加 MIME 类型的接受属性来向视图添加 javascript 验证整个解决方案可以找到< a href="http://www.jquery2dotnet.com/2013/05/how-to-create-and-editorfor-fileupload.html" rel="noreferrer">此处
If you are sure, that the source is image and doesn't need editing, you can do it easily as described here
To secure the file is image, add javascript validation to View by adding accept attribute with MIME type to input tag
and jQuery validation script
The whole solution can be found here