?
Solved

C# Graphics- Create larger canvas for image

Posted on 2011-10-17
3
Medium Priority
?
466 Views
Last Modified: 2012-05-12
I need to resize images in bulk for a web site I'm working on.  I have written a C# console app to take the images that are in a folder on the hard drive, and if they are larger than 400 px wide, resize them to 400px wide, calculating the height based on that width.  That is working with the attached code.


What I need help with is for images that are smaller than 400px wide.  I still want a 400px wide image, but I don't want to lose quality by resizing the image to 400px.  How can I create a canvas that is 400px wide and put the image on it in its original size?
originalimage = System.Drawing.Image.FromFile("C:\images")

oldheight = originalimage.Height;
oldwidth = originalimage.Width;
newheight = Convert.ToInt32((oldheight / oldwidth) * 400);
newhtint = Convert.ToInt32(newheight);

newimage = new System.Drawing.Bitmap(400, newhtint);

using (Graphics graphics = Graphics.FromImage(newimage))
{
  graphics.DrawImage(originalimage, new Rectangle(0, 0, newimage.Width, newimage.Height));
}

filename = "C:\\newimg\\" + li.Key + "image2m.jpg";
newimage.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);

newimage.Dispose();

Console.WriteLine("Large image created successfully for lot #" + li.Key + " image 2.");

Open in new window

0
Comment
Question by:cmerlo1
  • 2
3 Comments
 
LVL 14

Expert Comment

by:nishant joshi
ID: 36984118
try this...:-D
private bool resizeimage(string path2)
        {
            string fileName = "";
            try
            {
                int nwidth = 370;
                int nheight = 495;
                Size ThumbNailSize = new Size(nwidth, nheight);
                System.Drawing.Image oImg = System.Drawing.Image.FromFile(@"" + path2);
                System.Drawing.Image oThumbNail = new Bitmap(ThumbNailSize.Width, ThumbNailSize.Height);
                Graphics oGraphic = Graphics.FromImage(oThumbNail);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle oRectangle = new Rectangle(0, 0, ThumbNailSize.Width, ThumbNailSize.Height);
                oGraphic.DrawImage(oImg, oRectangle);
                FileInfo fi = new FileInfo(path2);
                if (fi.Extension.Equals(".jpg",StringComparison.CurrentCultureIgnoreCase) || fi.Extension.Equals(".jpeg",StringComparison.CurrentCultureIgnoreCase))
                {
                    fileName = fi.DirectoryName + "\\" + System.IO.Path.GetFileNameWithoutExtension(path2) + "new.jpg";
                    if (!File.Exists(fileName))
                    {
                        logstring = logstring +fileName+ "\n";
                        try
                        {
                            oThumbNail.Save(fileName, ImageFormat.Jpeg);
                        }
                        catch(Exception e)
                        {
                            MessageBox.Show("Cross Thread Error while saving image.\n" + fileName, con.Name + " Alert");
                        }
                        }
                    else
                    {
                        logstring = logstring + fileName + "*\n";
                    }
                }
                else if (fi.Extension.Equals(".bmp", StringComparison.CurrentCultureIgnoreCase))
                {
                    fileName = fi.DirectoryName + "\\" + System.IO.Path.GetFileNameWithoutExtension(path2) + "new.bmp";
                    if (!File.Exists(fileName))
                    {
                        logstring = logstring + fileName + "\n";
                        try
                        {
                        oThumbNail.Save(fileName, ImageFormat.Bmp);
                         }
                        catch(Exception e)
                        {
                           
                        }
                    }
                    else
                    {
                        logstring = logstring + fileName + "*\n";
                    }
                }
                else
                {
                    MessageBox.Show("Invalid Extension", con.Name + " Alert");
                }
                return true;
            }
            catch (Exception e)
            {

               
            }
        }

Open in new window

0
 

Accepted Solution

by:
cmerlo1 earned 0 total points
ID: 37117976
I figured it out:

graphics.FillRectangle(Brushes.Black, 0, 0, 400, newimage.Height);

                                int startpos = (400 - originalimage.Width) / 2;
                                graphics.DrawImage(originalimage, new Rectangle(startpos, 0, originalimage.Width, originalimage.Height));
0
 

Author Closing Comment

by:cmerlo1
ID: 37136771
I realized I needed to draw the canvas first.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

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

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question