When overlaying two identically-sized images, one is offset

戏子无情 提交于 2019-12-02 05:21:55

问题


I am attempting to create an image by overlaying one on top of another. The code works, but the image I am overlaying seems to be slightly stretched and I can't work out why.

So the code just creates a blank red 24x24 rectangle, then I overlay a 24x24 png file which looks like this:

What I am expecting is this:

But I actually get this:

Using backGround As New Bitmap(24, 24, Imaging.PixelFormat.Format32bppArgb)
        Using g = Graphics.FromImage(backGround)
            Using brush1 As New SolidBrush(Color.Red)
                g.FillRectangle(brush1, 0, 0, 24, 24)
                Using topimage = Image.FromFile("C:\Scratch\ManNoRecords24.png")
                    g.DrawImage(topimage, New Point(0, 0))
                End Using
            End Using
        End Using
        backGround.Save("C:\Scratch\Emp.png", Imaging.ImageFormat.Png)
    End Using

Debugger showing the properties of the topImage:


回答1:


You can use

g.DrawImageUnscaledAndClipped(topimage, New Rectangle(0, 0, 24, 24))

instead, to avoid any scaling of the source image while drawing it. This works but I am actually not quite sure what is wrong with your solution.

From the Reference Source, DrawImageUnscaledAndClipped seems to use Pixel as the default unit for the image size and hence ignores the DPI setting of the source image:

/// <include file='doc\Graphics.uex' path='docs/doc[@for="Graphics.DrawImageUnscaledAndClipped"]/*' />
/// <devdoc>
/// </devdoc>
public void DrawImageUnscaledAndClipped(Image image, Rectangle rect) {
    if(image == null) {
        throw new ArgumentNullException("image");
    }

    int width = Math.Min(rect.Width, image.Width);
    int height = Math.Min(rect.Height, image.Height);

    //We could put centering logic here too for the case when the image is smaller than the rect
    DrawImage(image, rect, 0, 0, width, height, GraphicsUnit.Pixel);
}

DrawImage and DrawImageUnscaled do not and then probably rescale the image based on its internal DPI setting, which Matt found out to be less than the default 96, which leads to stretching of the image:

/// <include file='doc\Graphics.uex' path='docs/doc[@for="Graphics.DrawImageUnscaled"]/*' />
/// <devdoc>
/// </devdoc>
public void DrawImageUnscaled(Image image, Point point) {
    DrawImage(image, point.X, point.Y);
}


来源:https://stackoverflow.com/questions/34879238/when-overlaying-two-identically-sized-images-one-is-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!