你如何将HttpPostedFileBase转换为图像? [英] How do you convert a HttpPostedFileBase to an Image?
问题描述
我正在使用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.
推荐答案
我使用 Image.FromStream
如下:
I use Image.FromStream
to as follows:
Image.FromStream(httpPostedFileBase.InputStream, true, true)
请注意返回的 Image
是 IDisposable
。
您需要引用系统.Drawing.dll
为此工作,图像
位于 System.Drawing
命名空间。
You'll need a reference to System.Drawing.dll
for this to work, and Image
is in the System.Drawing
namespace.
我不确定你要做什么,但如果你碰巧在制作缩略图或类似的东西,你可能有兴趣做类似的事情......
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...
try {
var bitmap = new Bitmap(newWidth,newHeight);
using (Graphics g = Graphics.FromImage(bitmap)) {
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(oldImage,
new Rectangle(0,0,newWidth,newHeight),
clipRectangle, GraphicsUnit.Pixel);
}//done with drawing on "g"
return bitmap;//transfer IDisposable ownership
} catch { //error before IDisposable ownership transfer
if (bitmap != null) bitmap.Dispose();
throw;
}
其中 clipRectangle
是您希望缩放到新位图的原始图像的矩形(您需要手动处理纵横比)。 catch-block是构造函数中典型的 IDisposable
用法;你保留新的 IDisposable
对象的所有权,直到它被返回(你可能想用代码注释来记录)。
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 typical IDisposable
usage inside a constructor; you maintain ownership of the new IDisposable
object until it is returned (you may want to doc that with code-comments).
不幸的是,默认的另存为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:
ImageCodecInfo jpgInfo = ImageCodecInfo.GetImageEncoders()
.Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();
using (EncoderParameters encParams = new EncoderParameters(1))
{
encParams.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality);
//quality should be in the range [0..100]
image.Save(outputStream, jpgInfo, encParams);
}
这篇关于你如何将HttpPostedFileBase转换为图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!