views:

343

answers:

5

I have a problem with image scaling in .NET. I use the standard Graphics type to resize images like in this example:

public static Image Scale(Image sourceImage, int destWidth, int destHeight)
{
        Bitmap toReturn = new Bitmap(sourceImage, destWidth, destHeight);

        toReturn.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);

        using (Graphics graphics = Graphics.FromImage(toReturn))
        {
            graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(sourceImage, 0, 0, destWidth, destHeight);
        }
        return toReturn;
    }

But I have a big problem with resized images: they have gray and black borders and it's extremely important to make have images without them.

Why do they appear and what I can to do make them disappear?

Sample Output:

image 370x370: http://www.freeimagehosting.net/image.php?a3be1bc837.jpg

+3  A: 

How does the following work for you? This is the code I've used to do the same thing. The main difference I notice is that I don't use SetResolution (and I assume a square input and output, since that was the case for me).

/// <summary>
/// Resizes a square image
/// </summary>
/// <param name="OriginalImage">Image to resize</param>
/// <param name="Size">Width and height of new image</param>
/// <returns>A scaled version of the image</returns>
internal static Image ResizeImage( Image OriginalImage, int Size )
{
    Image finalImage = new Bitmap( Size, Size );

    Graphics graphic = Graphics.FromImage( finalImage );

    graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

    Rectangle rectangle = new Rectangle( 0, 0, Size, Size );

    graphic.DrawImage( OriginalImage, rectangle );

    return finalImage;
}
Dov
+2  A: 

It's because sampling was taken from the edges of the photo.

Chuck Conway
+2  A: 

This is because of the smoothing (blending with the background) on the edges when drawing the image.

You could maybe draw it twice, once without and one with smoothing enabled. Or you could draw it a little bigger. Or if the original background color is known, you could first fill the image with the background color.

Lucero
+2  A: 

Try:

graphic.CompositingMode = CompositingModeSourceCopy;
Mark Ransom
A: 

Thanks!

set

graphic.CompositingMode = CompositingMode.SourceCopy;

solving this problem.

Evgeny