Introduction
It's not often that we work with extremely low-resolution, or pixelated images, but when we do we may have differing expectations of what that image should look like.
In a recent project I wanted to show the pixelation of the images, but when shown in the default PictureBox
, the pixelation could not be seen, because the control was smoothing the pixelation.
This is what I wanted (InterpolationType.NearestNeighbor
):
This is what I got (InterpolationType.Default
):
Background
Windows.Forms.Controls.PictureBox
is the standard control that is used to display images within a Windows Forms application. It does a decent job of this and offers some customization options, such as SizeMode
, to set how an image should fit in the box.
When displaying an image at any size other than the images original size i.e. pixel-to-pixel, the extra pixels used to turn a low-resolution image into a higher one, and vise-versa have to come from somewhere. This is called interpolation, and it turns out there are many algorithms to accomplish this.
PixelBox
is a custom control that is derived from PictureBox
. It adds the InterpolationMode
property, which has the effect of setting the GDI+ interpolation mode before the image is drawn onto the control's surface. The property is a value from the InterpolationMode enumeration.
The code
The changes to PictureBox
are quite simple. The entire class is shown below:
using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace RedCell.UI.Controls
{
public class PixelBox : PictureBox
{
#region Initialization
public PixelBox ()
{
InterpolationMode = InterpolationMode.Default;
}
#endregion
#region Properties
[Category("Behavior")]
[DefaultValue(InterpolationMode.Default)]
public InterpolationMode InterpolationMode { get; set; }
#endregion
#region Overrides of PictureBox
protected override void OnPaint (PaintEventArgs pe)
{
pe.Graphics.InterpolationMode = InterpolationMode;
base.OnPaint(pe);
}
#endregion
}
}
</see>
Demonstration
The demonstration application demonstrates any of the interpolation modes on a pixelated image. In addition to those shown above, here are the other modes for comparison:
InterpolationMode.Low
InterpolationMode.High
InterpolationMode.Bilinear
InterpolationMode.Bicubic
InterpolationMode.HighQualityBilinear
InterpolationMode.HighQualityBicubic
Conclusion
By subclassing PictureBox
and overriding its OnPaint
method we can set the GDI+ InterpolationMode
property, giving us greater control over the algorithm, quality, and speed of rendering.
History
- January 28, 2014
- Initial publication.