Question

I'm displaying images in a JS Carousel. The images are extremely large size so I shrink them down in the HTML. I do some math to maintain the aspect ratio. In the end though those large images reduce in quality. It should be noted these images already exist in the server and I'm NOT supposed to change the original file's size.

What is causing this reduced quality? Should I stick to smaller size images, increase the final size that will be displayed? Here's the code to help out, max width and height are currently 270 and 180 respectively. All of this is C#.

// srcccccc is the image file. Can be any kind of extension jpg, png, etc.
if (srcccccc != "")
{
    Globals.NavigateURL();
    string path = PortalSettings.HomeDirectory + srcccccc;
    using (System.Drawing.Image img = System.Drawing.Image.FromFile(@Server.MapPath(path)))
    {
        int[] newSizes = ResizeWithRatio(img);
        contentsall += "<img src=\"" + PortalSettings.HomeDirectory + srcccccc + "\" alt=\"Image "
            + folderidddin + "\" height=\"" + newSizes[1] + "px\"" + "\" width=\"" + newSizes[0] + "px\" />";
    }
}

// HTML is dynamically added later....

private int[] ResizeWithRatio(System.Drawing.Image img)
{
            int[] sizes = new int[2];
            if (img.Width > maxWidth || img.Height > maxHeight)
            {
                float ri = (float)img.Width / (float)img.Height;
                float rs = (float)maxWidth / (float)maxHeight;
                if (rs > ri)
                {
                    sizes[0] = (int)((float)img.Width * (float)maxHeight / (float)img.Height);
                    sizes[1] = maxHeight;
                }
                else
                {
                    sizes[0] = maxWidth;
                    sizes[1] = (int)((float)img.Height * (float)maxWidth / (float)img.Width);
                }
            }
            else
            {
                sizes[0] = img.Width;
                sizes[1] = img.Height;
            }
            return sizes;
}
Was it helpful?

Solution

The problem you are having is that you aren't scaling the image at all, you are telling the web browser to take the full size image and render it smaller. Browsers sadly are not very good at this and I think just use a very simple algorithm to do this.

The solution would be to scale the images on the server. I would suggest having a page handler which receives an image reference in some way (filename, id, etc.) and does the resizing before outputting to the client. The following question deals with the scaling in c#.

High Quality Image Scaling Library

OTHER TIPS

It is better if you shrink the images server side, have a look at this documentation. This will save network traffic and create better quality pictures.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top