How do you convert a HttpPostedFileBase to an Image?

匆匆过客 提交于 2019-12-17 17:26:28

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/1171696/how-do-you-convert-a-httppostedfilebase-to-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!