EMF 图像大小和分辨率因机器的缩放设置而异 - 在 C# 中创建时

Mei*_*. I 7 c# system.drawing image windows-10

我正在 C# 中创建 EMF 图像,缩放模式为 125%(请参阅文章底部更新的链接以更改 Windows 机器中的缩放模式)。无论代码中使用的 DPI 设置如何,图像大小和分辨率都会根据机器的缩放设置而变化。

        //Set the height and width of the EMF image
        int imageWidth = 1280;
        int imageHeight = 720;

        //Adjust the witdh for the screen resoultion 
        using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
        {
            imageWidth = (int)(imageWidth / 96.0 * graphics.DpiX);
            imageHeight = (int)(imageHeight / 96.0 * graphics.DpiY);
        }

        Image image = null;

        //Stream to create a EMF image
        MemoryStream stream = new MemoryStream();

        //Create graphics with bitmap and render the graphics in stream for EMF image
        using (Bitmap bitmap = new Bitmap(imageWidth, imageHeight))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                IntPtr hdc = g.GetHdc();
                Rectangle rect = new Rectangle(0, 0, imageWidth, imageHeight);
                image = new Metafile(stream, hdc, rect, MetafileFrameUnit.Pixel, EmfType.EmfPlusDual);
                g.ReleaseHdc();
            }
        }
        using (Graphics graphics = Graphics.FromImage(image))
        {
            SetGraphicsProperties(graphics);
            graphics.DrawRectangle(Pens.Black, new Rectangle(100, 100, 100, 100));
        }

        //This gives the expected resolution and file size regardless of scaling settigs of the windows machine
        image.Save("RasterImage.emf");
        image.Dispose();
        stream.Position = 0;

        //This gives the unexpected resolution and file size with different scaling settings in windows machine. Only works as expected when the scaling settings are set with 100%. Usually, I will dump this stream into a file-stream to get the vector graphics image.
        Image streamImg = Image.FromStream(stream);// Just for example, I used this Image.FromStream() method to repoduce the issue.
        streamImg.Save("StreamImage.emf");
        streamImg.Dispose();

    // Just to set the graphics properties
    internal static void SetGraphicsProperties(Graphics graphics)
    {
        graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.GammaCorrected;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.PageUnit = GraphicsUnit.Pixel;
    }
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我保存了两个图像。

  1. 光栅图像文件
  2. 流图像文件

两个图像都是用不同的分辨率和文件大小创建的。这在我的图纸中造成了一些缩放问题。

要更改 Windows 中的显示设置,请执行以下操作,

R单击桌面-> 显示设置-> 比例和布局(选择125%)

更改缩放比例的链接 - https://winaero.com/blog/set-display-custom-scaling-windows-10/

I am using windows 10. How to avoid these variations in image resolution and size?

Thanks, Meikandan