|
Tuesday, 17 October 2006 |
|
This code shows how to create thumbnails based on image files on server directory. Follow the steps below: //1- Put this code that calls the ImageUtil class Bitmap bmp = ImageUtil.createThumbnail("imagepath... .jpg", 100, 75); //2- It uses the image class below: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Drawing; using System.Drawing.Imaging; /// <summary> /// Summary description for ImageUtil /// </summary> public class ImageUtil { /// /// Creates a resized bitmap from an existing image on disk. /// Call Dispose on the returned Bitmap object /// /// Bitmap or null public static Bitmap createThumbnail(string lcFilename, int lnWidth, int lnHeight) { Bitmap bmpOut = null; try { Bitmap loBMP = new Bitmap(lcFilename); // ImageFormat loFormat = loBMP.RawFormat; decimal lnRatio; int lnNewWidth = 0; int lnNewHeight = 0; //*** If the image is smaller than a thumbnail just return it if (loBMP.Width < lnWidth && loBMP.Height < lnHeight) return loBMP; if (loBMP.Width > loBMP.Height) { lnRatio = (decimal)lnWidth / loBMP.Width; lnNewWidth = lnWidth; decimal lnTemp = loBMP.Height * lnRatio; lnNewHeight = (int)lnTemp; } else { lnRatio = (decimal)lnHeight / loBMP.Height; lnNewHeight = lnHeight; decimal lnTemp = loBMP.Width * lnRatio; lnNewWidth = (int)lnTemp; } // System.Drawing.Image imgOut = // loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,null,IntPtr.Zero); // *** This code creates cleaner (though bigger) thumbnails and properly // *** and handles GIF files better by generating a white background for // *** transparent images (as opposed to black) bmpOut = new Bitmap(lnNewWidth, lnNewHeight); Graphics g = Graphics.FromImage(bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight); g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight); loBMP.Dispose(); } catch { return null; } return bmpOut; } }
|
|
Last Updated ( Tuesday, 31 October 2006 )
|