InteropBitmap a BitmapImage
-
19-09-2019 - |
Pregunta
Estoy tratando de convertir un Bitmap (SystemIcons.Question)
a un BitmapImage
para que pueda utilizarlo en un control de imagen WPF.
Tengo el siguiente método para convertirlo en un BitmapSource
, pero devuelve un InteropBitmapImage
, ahora el problema es cómo convertir a un BitmapImage
. No parece un yeso directo a trabajar.
¿Alguien sabe cómo hacerlo?
CÓDIGO:
public BitmapSource ConvertToBitmapSource()
{
int width = SystemIcons.Question.Width;
int height = SystemIcons.Question.Height;
object a = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(SystemIcons.Question.ToBitmap().GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(width, height));
return (BitmapSource)a;
}
propiedad para volver BitmapImage: (a mi Bound Control de imagen)
public BitmapImage QuestionIcon
{
get
{
return (BitmapImage)ConvertToBitmapSource();
}
}
Solución
InteropBitmapImage
hereda de ImageSource
, por lo que se puede utilizar directamente en un control Image
. No es necesario que sea un BitmapImage
.
Otros consejos
Usted debe ser capaz de usar:
public BitmapImage QuestionIcon
{
get
{
using (MemoryStream ms = new MemoryStream())
{
System.Drawing.Bitmap dImg = SystemIcons.ToBitmap();
dImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
System.Windows.Media.Imaging.BitmapImage bImg = new System.Windows.Media.Imaging.BitmapImage();
bImg.BeginInit();
bImg.StreamSource = new MemoryStream(ms.ToArray());
bImg.EndInit();
return bImg;
}
}
}
public System.Windows.Media.Imaging.BitmapImage QuestionIcon
{
get
{
using (MemoryStream ms = new MemoryStream())
{
System.Drawing.Bitmap dImg = SystemIcons.ToBitmap();
dImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Position = 0;
var bImg = new System.Windows.Media.Imaging.BitmapImage();
bImg.BeginInit();
bImg.StreamSource = ms;
bImg.EndInit();
return bImg;
}
}
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow