.NET Logo
Welcome Guest Search | Active Topics | Members | Log In | Register

CodeToday: ResizeImage Options · View
ball
Posted: Monday, January 14, 2008 2:20:52 PM

Rank: อาจารย์
Groups: Administration

Joined: 12/1/2007
Posts: 473
Location: Bangkok

CodeToday: ResizeImage

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

 

public static void ResizeImage(string fileNameIn, string fileNameOut, int maxWidthOrHeight)
{
    // Open the image
    Bitmap bmpSource = new Bitmap(fileNameIn);

    Size originalSize = bmpSource.Size;
    Size newSize = new Size(0, 0);

    bmpSource.Dispose();

    decimal maxHeightDecimal = Convert.ToDecimal(maxWidthOrHeight);
    decimal maxWidthDecimal = Convert.ToDecimal(maxWidthOrHeight);

    decimal resizeFactor = 0;

    if (originalSize.Height > originalSize.Width)
    {
        // Portrait
        resizeFactor = Convert.ToDecimal(Decimal.Divide(originalSize.Height, maxHeightDecimal));
        newSize.Height = maxWidthOrHeight;
        newSize.Width = Convert.ToInt32(originalSize.Width / resizeFactor);
    }
    else
    {
        // Lanscape
        resizeFactor = Convert.ToDecimal(Decimal.Divide(originalSize.Width, maxWidthDecimal));
        newSize.Height = Convert.ToInt32(originalSize.Height / resizeFactor);
        newSize.Width = maxWidthOrHeight;
    }

    Bitmap mySourceBitmap = null;
    Bitmap myTargetBitmap = null;
    Graphics myGraphics = null;

    try
    {
        mySourceBitmap = new Bitmap(fileNameIn);

        int newWidth = newSize.Width;
        int newHeight = newSize.Height;

        myTargetBitmap = new Bitmap(mySourceBitmap, newWidth, newHeight);

        myGraphics = Graphics.FromImage(myTargetBitmap);

        myGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        mySourceBitmap.Dispose();

        // Save th new image
        myTargetBitmap.Save(fileNameOut, ImageFormat.Jpeg);
    }
    catch (Exception)
    {           
        throw;
    }
    finally
    {
        if (myGraphics != null) myGraphics.Dispose();
        if (mySourceBitmap != null) mySourceBitmap.Dispose();
        if (myTargetBitmap != null) myTargetBitmap.Dispose();
    }
}


Imagination is more Important than Knowledge... /A.Einstein
Users browsing this topic
Guest


Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Main Forum RSS : RSS

YAFVision Theme Created by Jaben Cargman (Tiny Gecko)
Powered by Yet Another Forum.net version 1.9.1.8 (NET v2.0) - 3/29/2008
Copyright © 2003-2008 Yet Another Forum.net. All rights reserved.


Sponsored by