A lot of times you find the need to load an image in C# so that you can modify it.
- Perhaps you want to create an image processing program.
- You may need to resize or rescale an image.
- Maybe you need to rotate an image.
- Possibly you want to replace some of the colors in the image.
Whatever the reason, it's easy to get started editing images and bitmaps in C#. The first thing you need to do is load the image off a drive.
C# Image Loading
The first thing that you need to do in order to edit an image is to either load one or get a bitmap handle to one. To load an image off a drive you can use the static ImageÃÂ class like this:
var bmp = (Bitmap) Image.FromFile(@"c:\temp\bitmap-flower.jpg");
This gives you a variable of type Bitmap that you can easily work with. Notice that we cast it to type Bitmap explicitly. If you do not do that then you will get back a variable of type Image which is not what we want. Once you have the Bitmap object you can start modifying it in RAM.
Lock the Image Bits
This step is not technically necessary but it makes image processing way, way faster and it's a great tool to add to your arsenal. You need to download a class called "LockBitmap.cs" and add it to your project.
- Download LockBitmap.cs hereÃÂ (right click the link and choose Save As)
The LockBitmap class was written byÃÂ Vano Maisuradze and originally published on CodeProject. Be sure to add the LockBitmap.cs file to your project. Once you have LockBitmap.cs in your project you can lock the bits like this:
var lockedBitmap = new LockBitmap(bmp);
lockedBitmap.LockBits();
With a locked Bitmap you can do all sorts of simple image modifications. The most important ones are:
lockedBitmap.Width
lockedBitmap.Height
lockedBitmap.GetPixel(x, y)
lockedBitmap.SetPixel(x, y, newColor)
ImageÃÂ Colors
In order to mess with colors in Bitmap images you need to know how to create colors. In the example above we passed "newColor" to the SetPixel function. You may be interested in our C# Color Object guide as well as our C# HTML Colors guide. newColor is a Color object which you can create using the static Color class. Color.FromArgb which expects Alpha (transparency), Reg, Green, and Blue integers. For instance, the color Red is:
newColor = Color.FromArgb(255, 255, 0, 0);
The first 255 is solid transparency, and the second 255 is full on red, while the last 2 zeros are no green and no blue.
SaveÃÂ Image
After you are done editing your image you may want to save it to a file. The only real challenge here is that you have to specify a compression routine to save the file with. The most common routines are JPG, GIF, and PNG. C# and .net make it pretty easy to save in any of these formats. Saving a Bitmap is a topic worthy of another guide to get it right.
C# Image Processing
We have a variety of C# Image Processing guides that you may be interested in.