在WPF/ c#中调整和处理ICO文件
本文关键字:处理 ICO 文件 调整 WPF | 更新日期: 2023-09-27 18:10:43
在我正在研究的一个应用程序中,有图像(System.Windows.Media.Imaging
的一部分)在XAML页面的代码后面动态创建并添加到窗口中。我正在使用ICO文件,它包含各种大小和位深度。我想要的大小是96x96 @ 32位。代码自动选择最大尺寸(256x256 @ 32位)。
我设置Image.Source
属性如下:
image.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/Images/Application.ico"));
现在,通过搜索,我找到了图标(System.Drawing
的一部分),这将允许我设置字符串路径和大小,但这是一个完全不同的库的一部分。
new Icon("pack://application:,,,/Resources/Images/Inquiry.ico",96,96);
任何想法我怎么能使我的图像的大小属性更易于管理?谢谢你!
编辑:将System.Drawing.Icon转换为System.Media.ImageSource
这篇文章让图像看起来更小,但是,如果我将图标设置为96x96或128x128并不重要,它实际上并没有改变显示图像的大小。我假设它将使用与System.Windows.Media.Imaging
默认值不同的默认值。
编辑到编辑:奇怪越来越奇怪。当我通过原始方法显示时,它肯定将图像显示为256x256。然而,当我使用链接中描述的转换方法时,当尺寸改变时,它们显着缩小(即256x256看起来更接近48x48)。
尝试在此回答中发布的标记扩展到另一个SO问题。注意,使用BitmapDecoder
从Ico文件中获取所需的帧。
您可以尝试使用以下代码,它应该适用于ICO文件:
Image displayImage = new Image();
// Create the source
BitmapImage sourceImage = new BitmapImage();
sourceImage.BeginInit();
sourceImage.UriSource = new Uri("pack://application:,,,/Resources/Images/Application.ico");
sourceImage.EndInit();
// Set the source
displayImage.Source = sourceImage;
// Set the size you want
displayImage.Width = 96;
displayImage.Stretch = Stretch.Uniform;
我没有尝试过ico文件,我认为在这里可能有用。
/// <summary>
/// Resizes image with high quality
/// </summary>
/// <param name="imgToResize">image to be resized</param>
/// <param name="size">new size</param>
/// <returns>new resized image</returns>
public Image GetResizedImage(Image imgToResize, Size size)
{
try
{
if (imgToResize != null && size != null)
{
if (imgToResize.Height == size.Height && imgToResize.Width == size.Width)
{
Image newImage = (Image)imgToResize.Clone();
imgToResize.Dispose();
return newImage;
}
else
{
Image newImage = (Image)imgToResize.Clone();
imgToResize.Dispose();
Bitmap b = new Bitmap(size.Width, size.Height);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(newImage, 0, 0, size.Width, size.Height);
g.Dispose();
return (Image)b;
}
}
return null;
}
catch (Exception e)
{
log.Error("Exception in Resizing an image ", e);
return null;
}
}