Home > Software, Web > Resize images for mobile web

Resize images for mobile web


If you decide that your mobile website won’t be nothing more than a translation of your website, then you have to look into resizing the images too. There are pretty good reasons for doing it:

  • mobile devices supports images only up to a certain file size
  • mobile devices supports images only up to a certain image width and height
  • mobile devices supports web pages only up to a certain total size (page + resources)
  • performance, when it comes to bandwidth
  • user experience, when it comes to rendering capabilities

Next, I will present a short and practical solution, implemented as an aspx page. The page is taking only one parameter (i), which is the URL of the original image, downloads it, resizes it and sends it back to the client. This can also be implemented as an HTTP filter as well: every time an image is requested, it gets the original image, resizes it and pushes it into the response. The advantage as a page is that you can process this way, even images from other servers.
As for how to recognize the user mobile device, we will use my favorite, WURFL. For more information see Mobile device recognition.

I will include here only the C# code with enough comments so I won’t need to say anything else.😀
But before, one more thing: what is the new size of the image? First of all we need the maximum image width and height supported by the user mobile device. Here, WURFL is the solution. Then I made the supposition that the images are optimized for 800×600 and I will reduce the image proportionally to the maximum width and height supported by the mobile device. To not give anomalies, I also introduce a minimum width and height, not to go below.

public partial class MobileImageResizer : System.Web.UI.Page
    {
        // image should not be reduce under this width
        private static int MIN_WIDTH = 24;
        // image should not be reduce under this height
        private static int MIN_HEIGHT = 24;
        // images on the desktop version are optimized for this width
        private static int OPTIMIZED_WIDTH = 800;
        // images on the desktop version are optimized for this height
        private static int OPTIMIZED_HEIGHT = 600;

        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            // get the image URL
            String url = context.Request.QueryString.Get("u");

            // if no URL is specified in the u parameter then send a NOT_FOUND error
            if (url == null)
            {
                Utils.Send(context.Response, HttpStatusCode.NotFound);
                return;
            }
            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            // specify a timeotu for the request
            // request.Timeout = 10000; // 10s
            // if you want use a proxy for request
            // request.Proxy = WebProxy;
            HttpWebResponse initialResponse = (HttpWebResponse)request.GetResponse();
                    
            // if something went wrong don't try to transform
            if (initialResponse.StatusCode != HttpStatusCode.OK)
                throw new HttpException((int)initialResponse.StatusCode, initialResponse.StatusDescription);

            context.Response.ContentType = initialResponse.ContentType;
            Image image = Bitmap.FromStream(initialResponse.GetResponseStream());

            // get the maximum image size from the WURFL database
            // see my other article about <a href="https://beradrian.wordpress.com/2008/09/04/mobile-device-filter-in-aspnet/">WURFL filter</a>
            int maxWidth = ...;
            int maxHeight = ...;

            // calculate the resize ratio
            double ratio = Math.Min( // final ratio
                    Math.Max( // final width ratio
                        ((double)maxWidth) / Math.Max(image.Width, OPTIMIZED_WIDTH), // width ratio
                        ((double)MIN_WIDTH) / image.Width // minimum width ratio
                    ),
                    Math.Max( // final height ratio
                        ((double)maxHeight) / Math.Max(image.Height, OPTIMIZED_HEIGHT), // height ratio
                        ((double)MIN_HEIGHT) / image.Height // minimum height ratio
                    )
                    );

            if (ratio &lt; 1)
            {
                // if we have to reduce the image
                int newWidth = (int)(image.Width * ratio);
                int newHeight = (int) (image.Height * ratio);

                Image newImage = new Bitmap(newWidth, newHeight, image.PixelFormat);
                Graphics g = Graphics.FromImage(newImage);
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle r = new Rectangle(0, 0, newWidth, newHeight);
                g.DrawImage(image, r);
                newImage.Save(context.Response.OutputStream, image.RawFormat);
            }
            else 
            {
                // otherwise simply send the image
                // we don't make bigger the smaller images
                image.Save(context.Response.OutputStream, image.RawFormat);
            }

            // finish
            context.Response.End();
        }
    }
Categories: Software, Web Tags: , , ,
  1. Richard
    May 22, 2009 at 3:09 am

    Some really usefull information here if you pay attention, thanks

  1. September 24, 2009 at 3:01 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: