Resizing images in C#

Just ran into a problem where I needed to resize images to fill (without distortion) a box of a defined height and width with high quality using C#. As I’m working with the Images as Streams to and from the database, my function takes and returns MemoryStream objects. It should be trivial to adjust the function to use Image objects as inputs and outputs instead.

The code I’ve written is below.

using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
 
...
 
private MemoryStream ResizeImageStream(MemoryStream stream, int boundingBoxWidth, int boundingBoxHeight)
{
    // One of the dimensions of the resultant image WILL be 'full size'.
    // i.e. The image will either have a width of boundingBoxWidth or a height of boundingBoxHeight.
    // This will happen whether the image needs to be shrunk or enlarged.
 
    Image imageToBeResized = Image.FromStream(stream);
 
    #region Derive the undistorted dimensions of the resized image.
    int imageResizeToHeight = (imageToBeResized.Height * boundingBoxWidth) / imageToBeResized.Width;
    int imageResizeToWidth = boundingBoxWidth;
 
    if (imageResizeToHeight >= boundingBoxHeight)
    {
        imageResizeToWidth = (imageResizeToWidth * boundingBoxHeight) / imageResizeToHeight;
        imageResizeToHeight = boundingBoxHeight;
    }
    #endregion
 
    #region Resize the image with high quality.
    Bitmap bitmap = new Bitmap(imageResizeToWidth, imageResizeToHeight);
 
    Graphics graphics = Graphics.FromImage(bitmap);
    graphics.SmoothingMode = SmoothingMode.AntiAlias;
    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;    
    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
 
    // Resize the image using the Graphics object.
    // As the Graphics object is tied to the Bitmap above, the resulting image will be in the Bitmap object.
    graphics.DrawImage(imageToBeResized, new Rectangle(0, 0, imageResizeToWidth, imageResizeToHeight));
 
    // Re-instantiate the stream in order to clean it out.
    stream = new MemoryStream();
 
    // Save the Bitmap into the MemoryStream as a PNG.
    bitmap.Save(stream, ImageFormat.Png);
    #endregion
 
    return stream;
}

Sorry We’re in Fargo

I love my state and I’m happily living in Fargo, however, after being inspired by Chris Welle’s tweet about Valuco, I just couldn’t help myself.

Sorry We're in Fargo

In order to design the sign in lieu of Valuco’s completion, I had to pickup a font similar to Valuco called Duke from the Lost Type Co-op. Duke itself is gorgeous as well and I think it looks great. Thanks for the fantastic fonts, guys!

Get the PDF – just print it on 8.5″ x 11″ with 0.5″ margins.

Updating Visual Studio 2010 with SP1

Visual Studio 2010I’ve been trying to get VS2010 SP1 to upgrade Visual Studio 2010 Professional for seemingly hours now, and I finally hit a breakthrough without having to reformat my machine (my preferred method of fixing software problems). When I had initially installed VS2010, I had let it install ‘everything’… i.e. support for C++, C#, F#, Web Development, etc. all out of the box. After uninstalling and reinstalling VS and minor VS SP1 cruft numerous times in an all out “bang-your-head-against-the-wall” method, I finally use the installer for VS2010 to reconfigure my installation and remove the components I wasn’t using – namely F# and C++ support. As I plan to use this installation for web development, the lack of C++ really isn’t much of a problem for me.

It was a shot in the dark, but it worked. I was able to install SP1 from here: Visual Studio 2010 SP1 Web Downloader

Finally, I get to move onto installing Lightswitch to find out what it’s all about!

Project Euler

I’ve been working on problems at Project Euler in order to help myself grow as a programmer as of late. While I haven’t completed many at this point, it’s been fun to think about algorithm design and problem solving with such ‘simple’ problems.

I’ve really liked working on them as they build upon one another. Subsequent problems normally build (from a logical sense) upon the algorithms of previous problems. For example, the first problem is “Add all the natural numbers below one thousand that are multiples of 3 or 5,” while the second problem is “Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.” Anyone can see how techniques developed for the first problem could be applied in the resolution of the second.

I definitely suggest visiting Project Euler to anyone who wants to code their way around a few brain teasers for fun!

WordPress Migration

At work we’re preparing to move data from one WordPress install to another, as part of an overall “let’s consolidate all our blogs under one roof” move. Of course, it’s not as easy as it should be.

First off, let me say this: I truly believe that WordPress is one of the best examples of open source on the planet, if not simply for its breakout popularity. While I don’t always agree with how certain bits were done in certain ways, there is more than one way to skin a cat.

That being said, however, I believe, as it stands, the migration utilities available could use some work. We’re moving Blog X from a 3.0.1 install to another 3.0.1 install, but it’s not as simple as just hitting export in the WordPress admin. Why? The importer seems to freak out once the import file becomes to large. Even though we’ve gone through the settings for WordPress and the underlying system, it begins to freak around 800 posts in. So, as a solution, we’re linking up the databases and running queries directly on the backend to migrate the data. Fortunately, however, this is pretty darn easy…

Even more stink comes in when one notices that Blog X is currently a standalone blog… and we’re trying to put it into another WordPress 3.0.1 install… one that we’re using as an MU system, and Blog X is no longer going to be the ‘main event’. I realize this isn’t a common issue, but it certainly would be nice if this worked a bit better. So, like I said, it’s not that bad. But, as the importer will tell you, “Upload your WordPress eXtended RSS (WXR) file and we’ll import the posts, pages, comments, custom fields, categories, and tags into this site.” That’s just great. However, I’ve got users. 2000+ users that need to move as well. This is no longer easy. I have had to come up with a way (along with a colleague’s generous assistance) to not only migrate the data on the DB side for each user (not so bad, honestly) but also to generate the correct associated folders and files in the filesystem (for avatars and the like) which turned out to be a complete pain in the rump.

However, launch day is next Tuesday. Maybe we’ll get lucky and all of our planning (3 test runs later) will pay off and showing up at 2AM to do this thing will prove to be far too cautious for what was actually needed. I certainly hope so.

In the end, all I really want is a user import feature to be a part of WordPress’ core functionality. I realize plugins exist, but we all know they need to update along with WordPress to stay stable and accurate. Please hear my plea, WordPress Development Team! Add a way to import users to the core so we don’t face the headaches again!

Wolfram|Alpha Widgets

A few days ago, Wolfram|Alpha released a beta of their widget creation tool. So far, I have to say I’m very impressed.

The tool allows developers (or anyone, really) to create customizable widgets that embody the results of queries, enhanced with dropdown menus, input boxes, and the like.

For example, say I wanted to add a tool to my blog post on ‘The Cost of Living’ that allowed visitors to compare their cost of living index with that of other regions. I could simply head over to Wolfram|Alpha Widgets, create an account, and start building. Simply put, for the first step I would try out some example queries until I receive the result I’m looking for. In this case, I’d do “Cost of Living Index Fargo, ND vs. New York, NY”. Through the next few steps, I’m able to replace different parts of that query with references to text inputs, allowing the end user to specify their own cities for comparison. After some color choices and descriptive text, I have myself a widget:

The widget builder is a dream to use and allows users to easily create and deploy user-friendly tools that leverage the power Wolfram|Alpha has to offer. I’ve been a big proponent of Wolfram|Alpha since it was launched in May of last year, and this tool gives me even more options to introduce it to others.


Other widgets I’ve built as proofs-of-concept:


Thoughts on Microsoft’s “Metro” UI

I have to say I’m pretty impressed thus far with Microsoft’s latest foray into the mobile space. Of course, Windows Phone 7 hasn’t yet been released, but I’m genuinely excited to use this product as soon as it becomes available. Why, you ask? The “Metro” UI, of course.

As stated in their UI Design and Interaction Guide,

The Metro design principles center on a look that uses type to echo the visual language of airport and metro system signage. The goal is to clearly direct end users to the content they want. Metro interfaces are supposed to embody harmonious, functional, and attractive visual elements.

From what I’ve seen thus far when interacting with both the Zune HD and a similarly designed Windows Media Center, this is yet another step in the right direction for Microsoft. The ease of use of the Zune HD is a testament to the fact that Microsoft is really pulling the right people and resources together to make UI their number one priority.

We can see their push for usability in their obvious attentiveness to what’s been working in the market these days (embodied so splendidly in Apple’s iOS). The design team has pulled together a rigid design document detailing specifications to make the system easier to use, rather than easier to program. I’m especially pleased that Microsoft is using the same techniques Apple and other touch-UI designers have pioneered to deliver a consistent paradigm across all of their devices, as well as those from other companies. They aren’t leaving the established gestures behind; they’re using what’s proven to work rather than coming up with different ways just for the sake of being different.

Overall, I’m pleased with what I’ve seen so far; Microsoft is really rising to the challenge in today’s mobile market with the Windows Phone 7′s “Metro” UI. They’re using proven concepts from across the board to enhance their experience, while simultaneously providing a simple, yet colorful UI that’s definitely uniquely entertaining. If things continue along this path, expect to hear a lot more about Windows Phone 7′s intuitive UI in the coming months.