最近用到C#中输出图像,需要确定图像实际宽高,网上找资料,大部分是说先获取实际宽度,然后获取宽方向的像素点数,计算比例即可。但获取到的宽度跟我测量的屏幕宽度不一致。DPI倒是获取正确,最后绕一圈使用了如下写法, 计算出来正确的宽度:
System.Windows.Forms.Panel p = new System.Windows.Forms.Panel();
System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(p.Handle);
IntPtr hdc = g.GetHdc();
int width = GetDeviceCaps(hdc, 4); // HORZRES
int pixels = GetDeviceCaps(hdc, 8); // BITSPIXEL
int dpi = GetDeviceCaps(hdc, 88);
width =(int)( pixels * 25.4 / dpi);
g.ReleaseHdc(hdc);
return (((double)pixels / (double)width) * (double)length);