Search code examples
c#resizethumbnails

Create thumbnail in .NET C# by defining width


I am using the following code in my website, for thumbnail creation:

string furl = "~/images/thumbs/" + matchString;
lBlogThumb.ImageUrl = GetThumbnailView(furl, 200, 200);


private string GetThumbnailView(string originalImagePath, int height, int width)
        {
            //Consider Image is stored at path like "ProductImage\\Product1.jpg"

            //Now we have created one another folder ProductThumbnail to store thumbnail image of product.
            //So let name of image be same, just change the FolderName while storing image.
            string thumbnailImagePath = originalImagePath.Replace("thumbs", "thumbs2");
            //If thumbnail Image is not available, generate it.
            if (!System.IO.File.Exists(Server.MapPath(thumbnailImagePath)))
            {
                System.Drawing.Image imThumbnailImage;
                System.Drawing.Image OriginalImage = System.Drawing.Image.FromFile(Server.MapPath(originalImagePath));
                imThumbnailImage = OriginalImage.GetThumbnailImage(width, height,
                             new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

                imThumbnailImage.Save(Server.MapPath(thumbnailImagePath), System.Drawing.Imaging.ImageFormat.Jpeg);

                imThumbnailImage.Dispose();
                OriginalImage.Dispose();
            }
            return thumbnailImagePath;
        }

public bool ThumbnailCallback() { return false; }

I would like to change this code, and be able to create a thumbnail defining width ONLY. What I have in mind is actually something like cropping/resizing image, using a static width, maintaining it's ratio. Is that possible;


Solution

  • let's have originalWidth=the original image width and thumbWidth. You can simply choose the thumbWidth to your desired value, and calculate the thumbHeigth=originalHeigth*thumbWidth/originalWidth