Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# C# .net Image Resizer

Posted on 2014-02-07
Medium Priority
313 Views
Hi

I have the following piece of code which resizes images to 620 pixels wide by 414 pixels high

Problem is when someone uploads a picture say 309 pixels wide by 414 pixels high it stretches the image to 620 pixels wide.

Anyone know how to amend this so if the width of a picture is less that 620 pixels wide it adds white space to either side of the image?

``````using System.Drawing;
using System.Drawing.Drawing2D;

public class ImageResizer
{
public static Image ResizeImage(Image image, Size size, bool preserveAspectRatio)
{
int newWidth;
int newHeight;
if (preserveAspectRatio)
{
int originalWidth = image.Width;
int originalHeight = image.Height;
float percentWidth = (float)size.Width / (float)originalWidth;
float percentHeight = (float)size.Height / (float)originalHeight;
float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
newWidth = (int)(originalWidth * percent);
newHeight = (int)(originalHeight * percent);
}
else
{
newWidth = size.Width;
newHeight = size.Height;
}
Image newImage = new Bitmap(newWidth, newHeight);
using (Graphics graphicsHandle = Graphics.FromImage(newImage))
{
graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}
}
``````
0
Question by:TPLLimited
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
1 Comment

LVL 19

Accepted Solution

Melih SARICA earned 1500 total points
ID: 39841551
Create a bitmap with white background
resize height
draw image on this bitmap.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Adults who share images on social media aren’t the only ones who need to worry about their privacy. Our culture’s tendency to share every move and celebration affects the privacy of our children, too.
When asking a question in a forum or creating documentation, screenshots are vital tools that can convey a lot more information and save you and your reader a lot of time
Users will learn how resize a batch of photos from a single command in Photoshop via Photoshop's Image Processor. Open up an Image you'd like to resize in Adobe Photoshop: Adjust the image size according to your preferences. Image > Adjustments > …
The goal of the tutorial is to teach the user the full work flow of how to use flash media encoder to stream onto YouTube.
###### Suggested Courses
Course of the Month5 days, 15 hours left to enroll