如何将 HttpPostedFileBase 转换为图像?

发布于 2024-07-27 20:47:20 字数 182 浏览 7 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月无声 2024-08-03 20:47:20

我使用 Image.FromStream 如下

Image.FromStream(httpPostedFileBase.InputStream, true, true)

:返回的ImageIDisposable

您需要引用 System.Drawing.dll 才能使其工作,并且 Image 位于 System.Drawing 命名空间中。

调整图像大小

我不确定您要做什么,但如果您碰巧正在制作缩略图或类似的东西,您可能会对做类似的事情感兴趣...

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 块是构造函数内典型的 IDisposable 用法; 您保留新的 IDisposable 对象的所有权,直到它返回为止(您可能需要使用代码注释来记录它)。

另存为 Jpeg

不幸的是,默认的“另存为 jpeg”编码器不会公开任何质量控制,并且选择非常低的默认质量。

不过,您也可以手动选择编码器,然后可以传递任意参数:

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);
}

I use Image.FromStream to as follows:

Image.FromStream(httpPostedFileBase.InputStream, true, true)

Note that the returned Image is IDisposable.

You'll need a reference to System.Drawing.dll for this to work, and Image is in the System.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...

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;
}

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).

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:

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);
}
二智少女 2024-08-03 20:47:20

如果您确定源是图像并且不需要编辑,您可以按照描述轻松完成 此处

[HttpPost]
public void Index(HttpPostedFileBase file)
{
    if (file.ContentLength > 0)
    {
        var filename = Path.GetFileName(file.FileName);

        System.Drawing.Image sourceimage =
            System.Drawing.Image.FromStream(file.InputStream);
    }
}

为了确保文件是图像,请通过向输入标记

<input type="file" accept="image/*">

和 jQuery 验证脚本

$.validator.addMethod('accept', function () { return true; });

添加 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

[HttpPost]
public void Index(HttpPostedFileBase file)
{
    if (file.ContentLength > 0)
    {
        var filename = Path.GetFileName(file.FileName);

        System.Drawing.Image sourceimage =
            System.Drawing.Image.FromStream(file.InputStream);
    }
}

To secure the file is image, add javascript validation to View by adding accept attribute with MIME type to input tag

<input type="file" accept="image/*">

and jQuery validation script

$.validator.addMethod('accept', function () { return true; });

The whole solution can be found here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文