I am creating EMF images in C# with scaling mode of 125% (Please refer the link updated in the bottom of the post to change the scaling mode in windows machine). The image size and resolution change, according to the machine's scaling settings regardless of the DPI settings in use in the code.
//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;
}
In the above code, I am saving two images.
- RasterImage.emf
- StreamImage.emf
Both images are created with different resolutions and file size. This makes some scaling issues in my drawings.
To change the display settings in windows please do the below,
RClick desktop-> Display Settings -> Scale and Layout (Choose 125%)
Link for changing the scaling - 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