C# 使用位图解码器时图标大小已更改。在WPF中创建
我们有一种将图标转换为给定大小的方法,如下所示:C# 使用位图解码器时图标大小已更改。在WPF中创建,c#,wpf,bitmap,bitmapimage,C#,Wpf,Bitmap,Bitmapimage,我们有一种将图标转换为给定大小的方法,如下所示: private BitmapFrame GetSizedSource(Icon icon, int size) { var stream = IconToStream(icon); var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand); var frame = dec
private BitmapFrame GetSizedSource(Icon icon, int size)
{
var stream = IconToStream(icon);
var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand);
var frame = decoder.Frames.SingleOrDefault(_ => Math.Abs(_.Width - size) < double.Epsilon);
return frame;
}
private Stream IconToStream(Icon icon)
{
using (var stream = new MemoryStream())
{
icon.Save(stream);
stream.Position = 0;
return stream;
}
}
private BitmapFrame GetSizedSource(图标,int-size)
{
var stream=IconToStream(图标);
var decoder=BitmapDecoder.Create(流,BitmapCreateOptions.DelayCreation,BitmapCacheOption.OnDemand);
var frame=decoder.Frames.SingleOrDefault(=>Math.Abs(u.Width-size)
当我们经过图标时,height/width
为32,参数size
为32
实际上,decoder.Frame[0]
width/height是1.0,我不知道为什么
我错过了什么吗?问题出在
IconToStream
中,它创建MemoryStream
,将图标复制到其中,返回引用,然后处理MemoryStream
分配的所有资源,从而有效地使流变为空。如果您将GetSizedSource
更改为以下类似的内容,在解除禁用MemoryStream
之前返回BitmapFrame
,则应该可以工作:
private BitmapFrame GetSizedSource(Icon icon, int size)
{
using (var stream = new MemoryStream())
{
icon.Save(stream);
stream.Position = 0;
return BitmapDecoder.Create(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand)
.Frames
.SingleOrDefault(_ => Math.Abs(_.Width - size) < double.Epsilon);
}
}
private BitmapFrame GetSizedSource(图标,int-size)
{
使用(var stream=new MemoryStream())
{
图标保存(流);
流位置=0;
返回BitmapDecoder.Create(流,BitmapCreateOptions.DelayCreation,BitmapCacheOption.OnDemand)
.框架
.SingleOrDefault(=>Math.Abs(u.Width-size)
宽度
和高度
是独立于设备的单位。您是否尝试过PixelWidth
和PixelHeight
?@dkozl是的,它们都是1
您是否尝试过使用(…)删除?您似乎创建了对它的流返回引用,然后处置了它的资源,事实上,这是一个已处置流的问题。若你们在处理前把镜框还给我,你们会没事的。