Pregunta

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?

¿Fue útil?

Solución

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);
   }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top