Pages

Thursday, December 8, 2011

Generate Thumbnail Images and Maintain Aspect Ratio

public class ThumbnailGenerator
    {
        /// <summary>
        /// Generates the thumbnail of given image.
        /// </summary>
        /// <param name="actualImagePath">The actual image path.</param>
        /// <param name="thumbnailPath">The thumbnail path.</param>
        /// <param name="thumbWidth">Width of the thumb.</param>
        /// <param name="thumbHeight">Height of the thumb.</param>
        public static void Generate(string actualImagePath, string thumbnailPath, int thumbWidth, int thumbHeight)
        {
            Image orignalImage = Image.FromFile(actualImagePath);
 
            // Rotating image 360 degrees to discart internal thumbnail image
            orignalImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
            orignalImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
 
            // Here is the basic formula to mantain aspect ratio
            // thumbHeight   imageHeight     
            // ----------- = -----------   
            // thumbWidth    imageWidth 
            //
            // Now lets assume that image width is greater and height is less and calculate the new height
            // So as per formula given above
            int newHeight = orignalImage.Height * thumbWidth / orignalImage.Width;
            int newWidth = thumbWidth;
 
            // New height is greater than our thumbHeight so we need to keep height fixed and calculate the width accordingly
            if (newHeight > thumbHeight)
            {
                newWidth = orignalImage.Width * thumbHeight / orignalImage.Height;
                newHeight = thumbHeight;
            }
 
            //Generate a thumbnail image
            Image thumbImage = orignalImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
 
            // Save resized picture
            var qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
            var quality = (long)100; //Image Quality 
            var ratio = new EncoderParameter(qualityEncoder, quality);
            var codecParams = new EncoderParameters(1);
            codecParams.Param[0] = ratio;
            //Right now I am saving JPEG only you can choose other formats as well
            var codecInfo = GetEncoder(ImageFormat.Jpeg);
 
            thumbImage.Save(thumbnailPath, codecInfo, codecParams);
 
            // Dispose unnecessory objects
            orignalImage.Dispose();
            thumbImage.Dispose();
        }
 
        /// <summary>
        /// Gets the encoder for particulat image format.
        /// </summary>
        /// <param name="format">Image format</param>
        /// <returns></returns>
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
    }

Call as :
ThumbnailGenerator.Generate(@"C:\images\Picture.jpg", @"C:\images\PictureThumb.jpg", 100, 150);

Print contents of Div using Javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <script language="javascript" type="text/javascript">
        function printDiv(divID) {
            //Get the HTML of div
            var divElements = document.getElementById(divID).innerHTML;
            //Get the HTML of whole page
            var oldPage = document.body.innerHTML;
           
            //Reset the page's HTML with div's HTML only
            document.body.innerHTML = "<html><head><title></title></head><body>" + divElements + "</body>";
           
            //Print Page
            window.print();
           
            //Restore orignal HTML
            document.body.innerHTML = oldPage;
           
            //disable postback on print button
            return false;
        }
    </script>
    <title>Div Printing Test Application by Zeeshan Umar</title>
</head>
<body>
    <form runat="server">
    <asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="return printDiv('div_print');" />
    <div id="garbage1">I am not going to be print</div>
    <div id="div_print"><h1 style="color: Red">Only Zeeshan Umar loves Asp.Net will be printed :D</h1></div>
    <div id="garbage2">I am not going to be print</div>
    </form>
</body>

Wednesday, December 7, 2011

Asp.net Cache Sliding Expiration and Absolute Expiration

Asp .Net provides two different ways to expire the cache on the basis of time. Here are two aproaches:-
  1. Sliding Expiration
  2. Absolute Expiration 
1. Absolute Expiration
Absolute expiration means that your data will be removed from cache after fixed amount of time either it is accessed or not. Generally we use it when we are displaying data which is changing but we can afford to display outdated data in our pages.  Mostly I put all of my dropdown values in cache with Absolute Expiration. Here is how you can code:-


 
DataTable dt = GetDataFromDatabase();
Cache.Insert("AbsoluteCacheKey", dt, null,
DateTime.Now.AddMinutes(1), //Data will expire after 1 minute
System.Web.Caching.Cache.NoSlidingExpiration);

2. Sliding Expiration
Sliding expiration means that your data will be removed from cache if that is not accessed for certain amount of time. Generally we store that data in this cache mode which is accessed many time on certain occasions. For example if you go in account settings section of a site, then you will be frequently accesing account information in that section. But most of the time you wont be using account setting's related data so there is no point of storing that data in cache. In such scenarios sliding expiration should be used. here is how you can save data in cache with sliding expiration:-
DataTable dt = GetDataFromDatabase();
Cache.Insert("SlidingExpiration", data, null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(1));//Data will be cached for 1 mins

Hopefully this information will be useful for you