<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users1869</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1869" rel="self"/>
  <title>tmeers.myopenid.com</title>
  <updated>Fri Jan 08 03:03:55 -0800 2010</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1136</id>
    <published>2010-01-08T03:03:55-08:00</published>
    <updated>2010-08-10T19:40:27-07:00</updated>
    <title>[C#] Image Resizing</title>
    <content type="html">&lt;p&gt;I'm really trying to nail out a little more performance out of this tidbit of code. It's not a heavily used bit of code but is used every time a new image is uploaded, and 4 times for each image (100px, 200px, 500px, 700px). So when there are any more than 2 or 3 images processing, it gets a little busy on the server. Also I'm trying to figure out how to make it correctly process images with a low resolution. Currently it just chops it off half way through, not plesent.&lt;/p&gt;

&lt;p&gt;Thanks! &lt;/p&gt;

&lt;pre&gt;public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
{
    using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
    {
        Size newSize = CalculateDimensions(oldImage.Size, targetSize);

        using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb))
        {
            newImage.SetResolution(oldImage.HorizontalResolution, oldImage.VerticalResolution);
            using (Graphics canvas = Graphics.FromImage(newImage))
            {
                canvas.SmoothingMode = SmoothingMode.AntiAlias;
                canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
                MemoryStream m = new MemoryStream();
                newImage.Save(m, ImageFormat.Jpeg);
                return m.GetBuffer();
            }
        }

    }
}

private static Size CalculateDimensions(Size oldSize, int targetSize)
{
    Size newSize = new Size();
    if (oldSize.Width &amp;gt; oldSize.Height)
    {
        newSize.Width = targetSize;
        newSize.Height = (int)(oldSize.Height * (float)targetSize / (float)oldSize.Width);
    }
    else
    {
        newSize.Width = (int)(oldSize.Width * (float)targetSize / (float)oldSize.Height);
        newSize.Height = targetSize;
    }
    return newSize;
}&lt;/pre&gt;</content>
    <author>
      <name>tmeers.myopenid.com</name>
      <email>no-email@refactormycode.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1136-image-resizing" rel="alternate"/>
  </entry>
</feed>

