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
每次记录一小步…点点滴滴人生路…