InteropBitmap à BitmapImage
-
19-09-2019 - |
Question
Je suis en train de convertir un Bitmap (SystemIcons.Question)
à un BitmapImage
pour que je puisse l'utiliser dans un contrôle d'image WPF.
J'ai la méthode suivante pour le convertir en un BitmapSource
, mais il renvoie un InteropBitmapImage
, maintenant le problème est de savoir comment convertir en un BitmapImage
. Une distribution directe ne semble pas fonctionner.
Quelqu'un sait comment le faire?
CODE:
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;
}
propriété pour retourner BitmapImage: (Bound à mon contrôle d'image)
public BitmapImage QuestionIcon
{
get
{
return (BitmapImage)ConvertToBitmapSource();
}
}
La solution
InteropBitmapImage
hérite de ImageSource
, de sorte que vous pouvez l'utiliser directement dans un contrôle Image
. Vous n'avez pas besoin d'être un BitmapImage
.
Autres conseils
Vous devriez pouvoir utiliser:
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;
}
}
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow