Image scaling causes poor quality in firefox/internet explorer but not chrome

前端 未结 10 1755
一个人的身影
一个人的身影 2020-11-27 03:44

See http://jsfiddle.net/aJ333/1/ in Chrome and then in either Firefox or Internet Explorer. The image is originally 120px, and I\'m scaling down to 28px, but it looks bad pr

10条回答
  •  旧巷少年郎
    2020-11-27 04:29

    One way to "normalize" the appearance in the different browsers is using your "server-side" to resize the image. An example using a C# controller:

    public ActionResult ResizeImage(string imageUrl, int width)
    {
        WebImage wImage = new WebImage(imageUrl);
        wImage = WebImageExtension.Resize(wImage, width);
        return File(wImage.GetBytes(), "image/png");
    }
    

    where WebImage is a class in System.Web.Helpers.

    WebImageExtension is defined below:

    using System.IO;
    using System.Web.Helpers;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Drawing.Drawing2D;
    using System.Collections.Generic;
    
    public static class WebImageExtension
    {
        private static readonly IDictionary TransparencyFormats =
            new Dictionary(StringComparer.OrdinalIgnoreCase) { { "png", ImageFormat.Png }, { "gif", ImageFormat.Gif } };
    
        public static WebImage Resize(this WebImage image, int width)
        {
            double aspectRatio = (double)image.Width / image.Height;
            var height = Convert.ToInt32(width / aspectRatio);
    
            ImageFormat format;
    
            if (!TransparencyFormats.TryGetValue(image.ImageFormat.ToLower(), out format))
            {
                return image.Resize(width, height);
            }
    
            using (Image resizedImage = new Bitmap(width, height))
            {
                using (var source = new Bitmap(new MemoryStream(image.GetBytes())))
                {
                    using (Graphics g = Graphics.FromImage(resizedImage))
                    {
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.DrawImage(source, 0, 0, width, height);
                    }
                }
    
                using (var ms = new MemoryStream())
                {
                    resizedImage.Save(ms, format);
                    return new WebImage(ms.ToArray());
                }
            }
        }
    }
    

    note the option InterpolationMode.HighQualityBicubic. This is the method used by Chrome.

    Now you need publish in a web page. Lets going use razor:

    
    

    And this worked very fine to me!

    Ideally will be better to save the image beforehand in diferent widths, using this resize algorithm, to avoid the controller process in every image load.

    (Sorry for my poor english, I'm brazilian...)

提交回复
热议问题