最近遇到图片加载显示到WPF的Image控件上,出现显示的问题。我的电脑显示器默认的DPI是96*96的,但是一开始没注意加载进来的图片的DPI值,导致图片加载进来后,图片的PixelHeight,PixelWidth的值和Height,Width比例有变化。
DPI是指每英寸的像素。所以DPI变化时,再像素高宽不变的情况下,图片的Height和Width会变化。
所以,当软件加载DPI为300*300的图片时,和再DPI为96*96的情况下会有变化。
如果想要加载图片后,达到相同的效果,则可以将加载进来的300*300的图片DPI修改为96*96后,再对图片进行操作。
下面是DPI转换的代码。
ImageSource source;
Bitmap newBitmap = BitmapFromSource((BitmapSource)source);
newBitmap.SetResolution(96, 96);
BitmapSource bitmapSource = getBitMapSourceFromBitmap(newBitmap);
source = bitmapSource;
下面是BitmapSource转Bitmap的代码
private Bitmap BitmapFromSource(BitmapSource bitmapsource)
{
Bitmap bitmap;
using (var outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(outStream);
bitmap = new Bitmap(outStream);
}
return bitmap;
}
下面是Bitmap转BitmapSource的代码
[DllImport("gdi32")]
int DeleteObject(IntPtr o);
/// <summary>
/// Bitmap->BitmapSource
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
public BitmapSource getBitMapSourceFromBitmap(Bitmap bitmap)
{
IntPtr intPtrl = bitmap.GetHbitmap();
BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(intPtrl,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
DeleteObject(intPtrl);
return bitmapSource;
}