我正在开发一个ASP.NET 3.5网络应用程序,我允许我的用户上传jpeg、gif、bmp或png图像.如果上传的图像尺寸大于103 x 32,我想将上传的图像调整为103 x 32.我读过一些博客帖子和文章,也try 过一些代码示例,但似乎没有什么效果.有人成功地做到了吗?

推荐答案

我前段时间也遇到过同样的问题,我是这样处理的:

private Image RezizeImage(Image img, int maxWidth, int maxHeight)
{
    if(img.Height < maxHeight && img.Width < maxWidth) return img;
    using (img)
    {
        Double xRatio = (double)img.Width / maxWidth;
        Double yRatio = (double)img.Height / maxHeight;
        Double ratio = Math.Max(xRatio, yRatio);
        int nnx = (int)Math.Floor(img.Width / ratio);
        int nny = (int)Math.Floor(img.Height / ratio);
        Bitmap cpy = new Bitmap(nnx, nny, PixelFormat.Format32bppArgb);
        using (Graphics gr = Graphics.FromImage(cpy))
        {
            gr.Clear(Color.Transparent);

            // This is said to give best quality when resizing images
            gr.InterpolationMode = InterpolationMode.HighQualityBicubic;

            gr.DrawImage(img,
                new Rectangle(0, 0, nnx, nny),
                new Rectangle(0, 0, img.Width, img.Height),
                GraphicsUnit.Pixel);
        }
        return cpy;
    }

}

private MemoryStream BytearrayToStream(byte[] arr)
{
    return new MemoryStream(arr, 0, arr.Length);
}

private void HandleImageUpload(byte[] binaryImage)
{
    Image img = RezizeImage(Image.FromStream(BytearrayToStream(binaryImage)), 103, 32);
    img.Save("IMAGELOCATION.png", System.Drawing.Imaging.ImageFormat.Gif);
}

我刚读到这是获得最高质量的方法.

Asp.net相关问答推荐

AJAX返回未定义、失败

C# - 将 xyz 平铺转换为纬度/经度,反之亦然,给出不同的结果

Windows 命令行中的/p:是什么意思

IIS HTTP 错误 500.19

模型项的类型为 CookMeIndexViewModel,但需要类型为 IEnumerable 的模型项

Web api 不支持 POST 方法

asp.net mvc 中的 RedirectToAction 用法

ASP.Net Core MVC - 自定义属性的客户端验证

没有回发的按钮?

无法使用单例Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor中的范围服务MyDbContext

ASP.NET vNext 与主机无关,这意味着什么?

在 asp.net 中将 JSON 转换为 .Net 对象时出错

.NET 上的 HTTP/2(HTTP2 或 SPDY)

存在 ios 7 虚拟键盘时,div 元素不会停留在底部

c# list 如何在两个值之间插入一个新值

Fiddler 没有从 ASP.NET 网站嗅探 SOAP 流量

使用 Web.Config 转换的高级任务

IsMobileDevice 是如何工作的?

~/ 等价于 javascript

如何使 URL 重写与 web.Release.config 转换一起工作?