C# Resized images have black borders

前端 未结 9 1256
长发绾君心
长发绾君心 2020-12-15 08:58

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 sourceIm         


        
相关标签:
9条回答
  • 2020-12-15 09:54

    The problem lies in the fact that your bitmap toReturn has a black background by default. Copying a new image over it makes black or gray borders.

    The solution is to remove the black default background, by calling:

    toReturn.MakeTransparent();
    

    Since after this line you'll be drawing on a new image without any background color the borders will disappear.

    0 讨论(0)
  • 2020-12-15 09:54

    This can be caused by pixels around the edges being wrongly interpolated. I'd call this a bug.

    Here's the solution, though:

    graphics.CompositingMode = CompositingMode.SourceCopy;
    graphics.PixelOffsetMode = PixelOffsetMode.Half;
    graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
    
    // Draw your image here.
    
    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    
    // Draw it again.
    

    What this does is first drawing a "background" with the edges correctly-filled, and then draw it again with interpolation. If you don't need interpolation, then this is not necessary.

    0 讨论(0)
  • 2020-12-15 09:55

    Try:

    graphic.CompositingMode = CompositingMode.SourceCopy;
    
    0 讨论(0)
提交回复
热议问题