Image Resizing by WPF: Using System.Windows.Media.Imaging;

Here is the example of getting resized image by using Imaging namespace in DotNet 3.0.

Same three reference need to add for resizing the image also. PresentationCore, WindowsBase and PresentationFramework.


private void ResizeImage(string SourceImagePath, string ImageType, string TargetImagePath, int decodePixelWidth, int decodePixelHeight)

{

newWidth = 0;

newHeight = 0;

getResizableHeightWidth(SourceImagePath, decodePixelWidth, decodePixelHeight);

byte[] imageBytes = LoadImageData(SourceImagePath);

ImageSource imageSource = CreateResizedImage(imageBytes, newWidth, newHeight);

imageBytes = GetEncodedImageData(imageSource, ImageType);

SaveImageData(imageBytes, TargetImagePath);

}

LoadImageData, GetEncodedImageData and SaveImageData methods are given in last post. Here the CreateResizedImage method is given in below.


//Method for getting resized image by given image data byte array with width and height.

ImageSource CreateResizedImage(byte[] imageData, int width, int height)

{

BitmapImage bmpImage = new BitmapImage();

bmpImage.BeginInit();

if (width > 0)

{

bmpImage.DecodePixelWidth = width;

}

if (height > 0)

{

bmpImage.DecodePixelHeight = height;

}

bmpImage.StreamSource = new MemoryStream(imageData);

bmpImage.CreateOptions = BitmapCreateOptions.None;

bmpImage.CacheOption = BitmapCacheOption.OnLoad;

bmpImage.EndInit();

Rect rect = new Rect(0, 0, width, height);

DrawingVisual drawingVisual = new DrawingVisual();

using (DrawingContext drawingContext = drawingVisual.RenderOpen())

{

drawingContext.DrawImage(bmpImage, rect);

}

RenderTargetBitmap resizedImage = new RenderTargetBitmap(

(int)rect.Width, (int)rect.Height, // Resized dimensions

96, 96, // Default DPI values

PixelFormats.Default); // Default pixel format

resizedImage.Render(drawingVisual);

return resizedImage;

}


//Method for getting resizable height and width by given height and width.

private void getResizableHeightWidth(string ImagePath, int maxWidth, int maxHeight)

{

System.Drawing.Image image = new Bitmap(ImagePath);

int width = image.Width;

int height = image.Height;

double widthFactor = (Convert.ToDouble(width) / Convert.ToDouble(maxWidth));

double heightFactor = (Convert.ToDouble(height) / Convert.ToDouble(maxHeight));

newWidth=0;

newHeight=0;

if (widthFactor > heightFactor)

{

newWidth = Convert.ToInt32(Convert.ToDouble(width) / widthFactor);

newHeight = Convert.ToInt32(Convert.ToDouble(height) / widthFactor);

}

else

{

newWidth = Convert.ToInt32(Convert.ToDouble(width) / heightFactor);

newHeight = Convert.ToInt32(Convert.ToDouble(height) / heightFactor);

}

if (newHeight == 0)

{

newHeight = 1;

}

if (newWidth == 0)

{

newWidth = 1;

}

}



That’s it.


...S.VinothkumaR.

1 comment:

Rajmohan said...

hi nice tutorial...........


raj4057