在 asp.net 中调整图像大小而不会降低图像质量 [英] Resizing an image in asp.net without losing the image quality

查看:28
本文介绍了在 asp.net 中调整图像大小而不会降低图像质量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 ASP.NET 3.5 Web 应用程序,我允许我的用户上传 jpeg、gif、bmp 或 png 图像.如果上传的图像尺寸大于 103 x 32,我想将上传的图像调整为 103 x 32.我阅读了一些博客文章和文章,也尝试了一些代码示例,但似乎没有任何效果.有没有人成功做到这一点?

I am developing an ASP.NET 3.5 web application in which I am allowing my users to upload either jpeg,gif,bmp or png images. If the uploaded image dimensions are greater then 103 x 32 the I want to resize the uploaded image to 103 x 32. I have read some blog posts and articles, and have also tried some of the code samples but nothing seems to work right. Has anyone succeed in doing this?

推荐答案

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

I had the same problem a while back and dealt with it this way:

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

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

I just read that this was the the way to get highest quality.

这篇关于在 asp.net 中调整图像大小而不会降低图像质量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆