简体   繁体   中英

Adding a frame to an Image (Bitmap) and Saving it - Error in Border

I am trying to open an image, add a border to it and save the image in C#.

I got a code, I guess it was an answer from stack overflow. Here it is:

    public Bitmap AddBorder(Bitmap image, Color color, int size)
    {
        Bitmap result = new Bitmap(image.Width + size * 2, image.Height + size * 2);
        Graphics g = Graphics.FromImage(result);
        g.Clear(color);
        int x = (result.Width - image.Width) / 2;
        int y = (result.Height - image.Height) / 2;
        g.DrawImage(image, new Point(x, y));
        g.Dispose();
        return result;
    }

I save the image using: resultimage.save(fileName);

I tested it with an image 5MP in size. And saved the image to the disk. But there is an error.

The result has a border in left side of it and on top of it. The image seems to be zoomed. For example the saved image would miss parts of it (from right size and bottom).

Am I doing any thing wrong?

Thanks in advance.

This will go wrong as described when the resolution of the input bitmap doesn't match the resolution of your video adapter. Something you can see with the debugger. Add watches for image.HorizontalResolution and result.HorizontalResolution . You'd only get a match by accident. DrawImage(Image, Point) will rescale the image to make the resolutions match so that the apparent size of the image is the same as on the machine on which the bitmap was designed.

You solve it by using the Graphics.DrawImage(Image, Rectangle) overload so you directly control the final size of the image. Fix:

   g.DrawImage(image, new Rectangle(x, y, image.Width, image.Height));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM