Help, my PDF images have white stripes

2/9/2012 By Marco Kesseler 0 comments

In PDF, there are often images that actually consist of a collection of smaller ones, neatly put next to each other.

Rendering these images seems easy enough in GDI+: just call the proper “DrawImage” method and that’s it. But then you discover that there are ugly stripes between the images.

PDF-image-with-white-stripes.png

What happens is the following: when the first of these images gets drawn, its edges are interpolated with the background color around the image, which is white at that point. This results in a smooth border that is almost completely white at the very edge. Then, when the neighbouring image gets drawn, its edges get interpolated again, this time with the lighter edge of the previous image.

All in all, the image edges get interpolated against a background color that actually should never have been visible in the first place.

A simple solution is to fool GDI+ and tell it that we do not intend to draw a single image, but that it is part of a tiling pattern where the images get flipped over both the X-axis and the Y-axis:

1 using (System.Drawing.Imaging.ImageAttributes attrs = new System.Drawing.Imaging.ImageAttributes()) 2 3 attrs.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY); 4 graphics.DrawImage ( 5 bitmap, 6 rectangle, 7 0, 0, width, height, 8 System.Drawing.GraphicsUnit.Pixel, attrs); 9 )

The image will be clipped against the given rectangle, so we won’t actually see any tiling happening, but GDI+ is now aware that the edges of the image are not drawn against a white background. In fact, it still interpolates de edges of each image, but it now does so against the edges of the neighboring (but invisible) tile, which has the same colors (that is why we need flipping):

PDF-image-no-stripes.png

There are of course also drawbacks to this technique: if an image has a very sharp transition near its edge, one still sees the interpolation happening. See the “belly” of the “S” below.

before-transistion.png

However, if we use some heuristics to avoid the tiling technique in certain cases we can largely avoid such issues:

after-transistion.png

We must admit that we are probably not the only ones that thought of this. The following image is from Adobe Reader X. It appears that it does something similar – see the top edge –, although of course it is impossible to say whether it really uses the same technique.

releated-techniques.png