DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Resize Image With .NET

  • submit to reddit
        using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
    Image original = Image.FromStream(new MemoryStream(imageFile));
    int targetH, targetW;
    if (original.Height > original.Width)
        targetH = targetSize;
        targetW = (int)(original.Width * ((float)targetSize / (float)original.Height));
        targetW = targetSize;
        targetH = (int)(original.Height * ((float)targetSize / (float)original.Width));
    Image imgPhoto = Image.FromStream(new MemoryStream(imageFile));
    // Create a new blank canvas.  The resized image will be drawn on this canvas.
    Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
    bmPhoto.SetResolution(72, 72);
    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
    grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
    grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);
    // Save out to memory and then to a file.  We dispose of all objects to make sure the files don't stay locked.
    MemoryStream mm = new MemoryStream();
    bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
    return mm.GetBuffer();


Nathanael Jones replied on Mon, 2011/05/30 - 2:38pm

There are so many things wrong with this code.... from the inefficient double-loading of the image, to the lack of using(){} statements... to ... nevermind.... Just Google "image resizing pitfalls", you'll see this article...... Leaking memory isn't so bad in a client app, but if you're doing GDI stuff in an ASP.NET app, you shouldn't be.... At least use a library designed to avoid all the GDI bugs and pitfalls.

Snippets Manager replied on Fri, 2006/02/10 - 8:57pm

This code is usefull, especially with ASP.NET. I used a similar algorithm that I wrote myself to resize images that were uploaded to my ASP.NET web application, but I did not set the Interpolation Mode or Pixel Offset Mode. That's a new one, even for me.