Image Scaling with GDI+ Part 3: DrawImage() and the Settings that Affect It
- Posted in:
In my last post, I covered some of the high-level features in my reference System.Drawing/GDI+ resizer. In this post, I’ll be discussing some of the options on the Graphics and ImageAttributes classes that affect the image quality and scaling/rendering performance of Graphics.DrawImage(). I’ve seen a lot of misinformation around the web when it comes to these settings, some of it even coming directly from MSDN. The GDI+ documentation is much more complete and accurate than the documentation for the System.Drawing wrappers, but even then, some of the concepts can be foreign to developers without a background in image processing. I’ll attempt to describe them better and with concrete examples.
The important thing to take away from this is that each of these settings and its corresponding values are designed to address a specific facet of image quality. There’s no secret combination that unlocks image processing nirvana. If quality is your only concern, you can set all the HighQuality options and know you’re getting the best GDI+ can do, but you’ll pay an unnecessary performance penalty (we saw examples of that in Part 1 of this series). If you want the best quality with the best performance possible, you’ll need to learn what the options do individually so you know when and how to use them. There actually aren’t that many.
This setting is the most important and perhaps the least understood, so there’s a lot to say here. I’ll be doing an entire post on it, in fact (I know, I’m a tease). For now, I’ll just say that unless you have a good reason not to, you should always use
InterpolationMode.HighQualityBicubic, which is the highest quality interpolator available in GDI+. It’s also the slowest, but you get what you pay for…
One of the more common complaints you’ll see about DrawImage() is that it produces artifacts around the edges of images. I can show my own example of the artifacts in question by resizing a solid grey image using InterpolationMode.HighQualityBicubic and the default values for the remainder of the settings on the Bitmap and Graphics objects. I opened the resulting image and zoomed in (15x) on the corner.
You can see two things going on here. First, the outermost edges have the transparency grid showing through in my viewer, so they’re not completely opaque, which is strange considering the original image didn’t have an alpha channel. Second, there is a lighter 1 pixel wide line set 1 pixel in. That lighter color also doesn’t appear anywhere in the original image. Note that if I saved this image in a format that didn’t support transparency (like JPEG), the semi-transparent pixels would be blended with black instead and would show up darker grey. That was the complaint in the stackoverflow question I linked above.
What we’re seeing in this case is the result of several factors.
- GDI+ starts with a blank (transparent or black – depending on your PixelFormat) canvas and draws your resized image on top of that.
- The HighQuality scalers in GDI+ do their image scaling in RGBA mode, even if neither your source nor destination image is RGBA.
- GDI+ doesn’t handle edge pixels correctly by default.
- The HighQualityBicubic interpolator has sharpening properties.
- GDI+ doesn’t handle sharpening with transparency correctly.
There’s nothing you can do about the first two points. That’s just how DrawImage() works.
The last two points are the cause of the lighter lines, and they can be negated by using a non-sharpening interpolator. Here’s the same image resized with the HighQualityBilinear interpolator, which smooths rather than sharpens. The lines have been eliminated, but the semi-transparent edge pixels remain.
Finally, if we use the plain Bilinear interpolator, which has a smaller sampling range, we get the solid image we expected.
Yeah, I know… I said to always use HighQualityBicubic…
The reason using a lower quality interpolator fixed the issue is the third point I mentioned above. GDI+ doesn’t handle edge pixels the same way most image scalers do. Imagine your source image is sitting in the middle (if there is such a thing) an infinite transparent plane. During the resize, any time the interpolator tries to sample pixel data that falls outside the bounds of the original image, it has nothing but transparent pixels to use. Both of the HighQuality interpolators in GDI+ use convolution kernels that require pixels from beyond the image edges. Most image scalers will simply extend the edge pixels outward to get the correct results, but GDI+ doesn’t do that. To get the desired behavior, you must use an overload of DrawImage() that accepts an ImageAttributes object.
ImageAttributes has a WrapMode property that allows you to tell GDI+ to tile the input image across that imaginary infinite plane to fill in the pixels beyond the edges. The closest you can get to a normal implementation is to mirror the edge pixels in all directions, by using
ImageAttributes.SetWrapMode(WrapMode.TileFlipXY). This ensures that there are always valid pixels to sample, and you’ll get the expected behavior for the edge pixels. Don’t worry, it’s not as expensive as it sounds, and the quality tradeoff is worth it. I won’t bother with a sample image… it’s just a grey square like the one above, as you’d expect, no matter which interpolator you choose.
My point about GDI+ not handling sharpening with transparency correctly still stands, though. If your image contains a transition from transparent to opaque somewhere in the middle of the image, you’ll get the same type of artifacts we saw above, and the WrapMode won’t help you, because the edge pixels aren’t the issue. Below is the result when resizing an opaque grey square surrounded by a transparent border. Here I’ve used InterpolationMode.HighQualityBicubic with WrapMode.TileFlipXY.
You can see the artifacts are back, now appearing in the middle of the image instead of on the edge. There’s no complete fix for that (see the next section for a partial fix), other than to use a non-sharpening interpolator… or to use a different scaler (like MagicScaler) that handles sharpening and transparency correctly.
Looking at the System.Drawing docs, it appears you have five settings available for PixelOffsetMode. They make some vague references to a tradeoff between quality and speed to differentiate them, and they even manage to get those wrong. Contrast that with the GDI+ docs for the same setting. Those docs make it clear; there are really only two options, and the Remarks section describes quite nicely what each does. The real options: None and Half. The rest are just aliases for those two. I’ll make it even simpler: None=Bad, Half=Good. The default value is Bad. While there may technically be a performance difference between the two, it’s not measurable. The quality difference most certainly is. In the following example I have resized a 3x3 pixel checkerboard grid to 100x100 using the NearestNeighbor interpolator, first with the default mode and then the correct one.
The results speak for themselves. You should always set the PixelOffsetMode to Half or HighQuality (same thing) when using DrawImage().
That said, I have to admit that my examples from the section on WrapMode used PixelOffsetMode.None to accentuate the artifacts. Had I used Half/HighQuality, the artifacts would still be present, but they would be more faint. Here are those two examples redone with PixelOffsetMode.Half. In order to show the edge artifacts in the first image, I have not set the WrapMode.
Again, setting both
WrapMode.TileFlipXY gives you the best quality GDI+ has to offer. That will completely correct the artifacts at the image edge and will give the result above on a hard transition from transparent to opaque away from the edge. Depending on your viewing environment, the artifacts in that one may be quite difficult to see now. If you can’t see them, just take my word for it; they’re there.
This is an interesting one in that the default value (CompositingMode.SourceOver) is the more expensive option. Every other Graphics setting defaults to lower quality/higher speed. SourceOver is what you want if you’re actually blending multiple layers, but you’ll incur an unnecessary performance hit if you’re not. In a simple image resizing scenario, you’re compositing the resized image over a blank background, so there’s no need to calculate any blending between those layers. You can, in these cases, set the value to SourceCopy (which simply overwrites the bottom layer with the top) to get better performance. If, however, you’re applying a background matte to a partially transparent image, drawing text over an image, or blending multiple images together, you’ll want to use the default value of SourceOver.
In my reference resizer, to maximize performance, I set the value to SourceCopy by default and switch to SourceOver only if matting is requested.
This one is my favorite, if only because this is the setting that I read the most crazy things about on teh internets. It can also be a big performance killer.
Much like PixelOffsetMode, there’s a gulf in quality between the System.Drawing docs and the GDI+ docs for CompositingQuality. The .NET documentation again presents you with five options and only vague comments about speed vs. quality to help you choose between them. The Remarks are even worse on this one, claiming differences in performance and quality between two aliases for the same value. They also say something about surrounding pixels being taken into account, which is complete nonsense. The GDI+ docs are much more clear about what the real options are and what they actually do. In this case, as before, there are really two options: AssumeLinear and GammaCorrected. AssumeLinear=Bad, GammaCorrected=Good. The default is Bad. See this MinutePhysics video for a simplified explanation of the difference. The math is dumbed down in the video, but you’ll get the idea. The real math can be found in the sRGB spec if you’re interested.
For my example, I’ll blend green and red as they do in the video so you can see the effect. I start with an image that has a gradient from green to transparent (shown here over a transparency grid). I then matte that over a red background to see how they blend.
Note that the image on the right blends smoothly (Good) while the middle image shows a dark, muddy line where the colors blend (Bad).
The trick in this case is that doing gamma-corrected blending is much more expensive than doing it the wrong way, so the speed vs. quality tradeoff is very real this time. When using CompositingMode.SourceOver with CompositingQuality.GammaCorrected, you will have a measurable performance hit. Again, in my reference resizer, I apply those settings only if a matte is being applied to a partially transparent image. For normal image scaling, there’s no need; you’ll only be slowing things down, potentially a lot.
Unless you’re drawing vector shapes on top of your image, this setting has no effect. It doesn’t affect DrawImage(), nor does it affect text rendering. I see lots of developers including it in their image resizing code, but for the most part, they’re just wildly setting anything with HighQuality in the name because the documentation does such a poor job of explaining what the settings actually do, and they can’t be bothered to dig deeper. It’s not harmful; it’s just a throwaway line of code for the cargo cult. My reference resizer does no drawing, so it doesn’t set a SmoothingMode.
Tune in next time for my detailed examination of the GDI+ InterpolationMode values.
Questions? Suggestions? Sound off in the comments.