InteropBitmap a BitmapImage
-
19-09-2019 - |
Domanda
Sto cercando di convertire un Bitmap (SystemIcons.Question)
ad un BitmapImage
modo da poter utilizzare in un controllo Image WPF.
Ho il seguente metodo per convertirlo in un BitmapSource
, ma restituisce un InteropBitmapImage
, ora il problema è come convertirlo in un BitmapImage
. Un cast diretta non sembra funzionare.
Qualcuno sa come fare?
codice:
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;
}
proprietà per tornare BitmapImage: (Bound alla mia Image Control)
public BitmapImage QuestionIcon
{
get
{
return (BitmapImage)ConvertToBitmapSource();
}
}
Soluzione
InteropBitmapImage
eredita da ImageSource
, in modo da poter utilizzare direttamente in un controllo Image
. Non è necessario che sia un BitmapImage
.
Altri suggerimenti
Si dovrebbe essere in grado di utilizzare:
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;
}
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow