문제

We have a method to Convert icon to given size, which likes below:

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;
    }
}

As we pass the icon, which height/width is 32, and parameter size is 32.

Actually, the decoder.Frame[0] width/height is 1.0, I don't know why?

Did I miss something?

도움이 되었습니까?

해결책

Problem is in IconToStream which creates MemoryStream, copies icon into it, returns reference and then disposes all resources allocated by MemoryStream which effectively makes your stream and therefore Frame empty. If you would change GetSizedSource to something like below that returns BitmapFrame before desposing MemoryStream is should work:

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);
   }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top