WPF 修改圖片的分辨率/DPI
在WPF中,當使用到PNG之類的圖片作爲背景時。我發現一個問題:圖片屬性(Windows)的寬、高相同的兩張圖片在WPF界面上顯示卻大小不一。如下圖所示。
在後臺應用程序調試時發現,兩個圖片的DPI不一致。
2.png
3.png
百度了下,網友提供了三種解決方法:
-
創建 BitmapImage 對象,根據當前屏幕的 DPI 值計算 DecodePixelWidth 和 DecodePixelHeight ;
-
創建 DrawingImage 對象,直接按照 WPF 的座標單位繪製圖片原始像素大小的圖片;
-
創建 Bitmap / WriteableBitmap 對象,重新創建一張 96 DPI 的圖片。
嘗試了下,沒走通,於是另闢蹊徑。
在調試的時候,發現Biamap生成的時候DPI已經是299了,因此將目光轉到了修改Biamap的DPI。
方法1:
1.將圖片加載成bitmap格式,然後轉換成BitmapImage格式
/// <summary>
/// 圖片轉換
/// </summary>
/// <param name="bitmap">bitmap格式圖片</param>
/// <returns></returns>
private static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
// 直接設置DPI
bitmap.SetResolution(96, 96);
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
2.使用
ib2.ImageSource = BitmapToBitmapImage(new System.Drawing.Bitmap(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "3.png")));
說明:ib2是一個畫刷(ImageBrush)。
但是好像在Win7下面這個方法失效了。
方法2:
思路:重新生成一個Bitmap,將原來的從文件資源加載上來的Bitmap繪製到新的Bitmap上。然後再用新的Bitmap去轉換成BitmapImage格式。
Bitmap轉換方法:
/// <summary>
/// 轉換Bitmap類型,通過GDI重新獲取一個新的Bitmap。
/// </summary>
/// <param name="imagePath">原圖片的路徑</param>
/// <returns></returns>
private Bitmap TranslateBitmap(string imagePath)
{
// 返回的
Bitmap result = null;
using (FileStream fs = new FileStream(imagePath, FileMode.Open))
{
// 原圖片信息
Bitmap orignal = new Bitmap(fs);
// 注意:如果是要透明的圖片就需要使用 Format32bppPArgb 格式,具有Alpha透明度。
result = new Bitmap(orignal.Width, orignal.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
// 設置 DPI 信息,後來測試發現不用設置
//result.SetResolution(96.0F, 96.0F);
// 使用GDI畫圖
using (Graphics g = Graphics.FromImage(result))
{
g.Clear(System.Drawing.Color.Transparent);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(orignal, new System.Drawing.Rectangle(0, 0, result.Width, result.Height), 0, 0, orignal.Width, orignal.Height, GraphicsUnit.Pixel);
g.Dispose();
}
}
return result;
}
然後稍微修改下BitmapToBitmapImage方法:
/// <summary>
/// 圖片轉換
/// </summary>
/// <param name="bitmap">bitmap格式圖片</param>
/// <returns></returns>
private static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
問題解決了。
Over
每次記錄一小步…點點滴滴人生路…