InteropBitmap para BitmapImage
-
19-09-2019 - |
Pergunta
Eu estou tentando converter um Bitmap (SystemIcons.Question)
a um BitmapImage
para que eu possa usá-lo em uma WPF controle de imagem.
Eu tenho o seguinte método para convertê-lo em um BitmapSource
, mas ele retorna um InteropBitmapImage
, agora o problema é como convertê-lo a um BitmapImage
. Um elenco direta não parece trabalho.
Alguém sabe como fazê-lo?
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;
}
propriedade para retornar BitmapImage: (ligada à minha Controle de Imagem)
public BitmapImage QuestionIcon
{
get
{
return (BitmapImage)ConvertToBitmapSource();
}
}
Solução
herda InteropBitmapImage
de ImageSource
, assim você pode usá-lo diretamente em um controle Image
. Você não precisa dele para ser um BitmapImage
.
Outras dicas
Você deve 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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow