简体   繁体   English

HttpPostedFileBase调整图像大小

[英]HttpPostedFileBase to Resized Image

I have the following line of code which takes my HttpPostedFileBase and converts it to an image. 我有以下代码行将我的HttpPostedFileBase转换为图像。

I have messed around with Encoder Parameteres to try and resize the image but can't seem to do this. 我弄乱了Encoder Parameteres尝试调整图像的大小,但似乎无法做到这一点。

What is the best way to resize the image to 250x250? 将图片尺寸调整为250x250的最佳方法是什么?

I would also prefer it to take the middle of the image as 250x250 rectangle rather than somewhere random. 我也希望它以图像的中间为250x250矩形,而不是随机的某个地方。

What is the most space efficent way to convert and save the image as it will be going in the database? 转换和保存图像的最节省空间的方法是什么,因为它将在数据库中进行处理?

Please note that model.Image is of type HttpPostedFileBase . 请注意, model.Image的类型HttpPostedFileBase

var image = Image.FromStream(model.Image.InputStream, true, true);

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

    //quality should be in the range [0..100]
    using (var ms = new MemoryStream())
    {
        // Convert Image to byte[]
        image.Save(ms, ImageFormat.Jpeg);
        byte[] imageBytes = ms.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        image64 = base64String;
    }
}

The best way is to use an established library like ImageResizer ; 最好的方法是使用已建立的库,例如ImageResizer that way, you avoid re-inventing the wheel. 这样,您就可以避免重新发明轮子。 If you are concerned about space efficiency (file size), use the JPEG format with maximum compression. 如果您担心空间效率(文件大小),请使用具有最大压缩率的JPEG格式。 Note that using JPEG's lossy encoding will drastically reduce image quality. 请注意,使用JPEG的有损编码会大大降低图像质量。 If you want to use a lossless encoding, try PNG. 如果要使用无损编码,请尝试使用PNG。 Compressing PNG images is quite difficult in .NET, in my experience. 根据我的经验,在.NET中压缩PNG图像非常困难。 I searched in vain awhile back for a single library that would do it and all I found were thick-client Windows applications. 不久之前,我徒劳地搜索了一个可以做到这一点的库,而我发现的所有库都是胖客户端Windows应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM