web-dev-qa-db-fra.com

WPF - conversion de Bitmap en ImageSource

J'ai besoin de convertir un System.Drawing.Bitmap en classe System.Windows.Media.ImageSource afin de le lier en un contrôle HeaderImage d'un WizardPage (boîte à outils WPF étendue). Le bitmap est défini comme une ressource de l'assemblage que j'écris. Il est référencé comme ça:

     public Bitmap GetBitmap
     {
         get
         {
             Bitmap bitmap = new Bitmap(Resources.my_banner);
             return bitmap;
         }
     }

     public ImageSource HeaderBitmap
     {
         get
         {
             ImageSourceConverter c = new ImageSourceConverter();
             return (ImageSource) c.ConvertFrom(GetBitmap);
         }
     }

J'ai trouvé le convertisseur ici: http://www.codeproject.com/Questions/621920/How-to-convert-Bitmap-to-ImageSource Je reçois une exception NullReferenceException sur

return (ImageSource) c.ConvertFrom(Resources.my_banner); Comment puis-je initialiser ImageSource afin d'éviter cette exception? Ou existe-t-il un autre moyen? Je veux l'utiliser ensuite comme:

        <xctk:WizardPage x:Name="StartPage" Height="500" Width="700"
                     HeaderImage="{Binding HeaderBitmap}" Enter="StartPage_OnEnter"

Merci d'avance pour n'importe quelle réponse.

20
user3489135

Pour d'autres, cela fonctionne:

    //If you get 'dllimport unknown'-, then add 'using System.Runtime.InteropServices;'
    [DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool DeleteObject([In] IntPtr hObject);

    public ImageSource ImageSourceFromBitmap(Bitmap bmp)
    {
        var handle = bmp.GetHbitmap();
        try
        {
            return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
        }
        finally { DeleteObject(handle); }               
    }
24
dethSwatch

Pour le bénéfice des chercheurs, j'ai créé un convertisseur rapide basé sur un ceci plus solution détaillée .

Aucun problème jusqu'à présent.

using System;
using System.Drawing;
using System.IO;
using System.Windows.Media.Imaging;

namespace XYZ.Helpers
{
    public class ConvertBitmapToBitmapImage
    {
        /// <summary>
        /// Takes a bitmap and converts it to an image that can be handled by WPF ImageBrush
        /// </summary>
        /// <param name="src">A bitmap image</param>
        /// <returns>The image as a BitmapImage for WPF</returns>
        public BitmapImage Convert(Bitmap src)
        {
            MemoryStream ms = new MemoryStream();
            ((System.Drawing.Bitmap)src).Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            ms.Seek(0, SeekOrigin.Begin);
            image.StreamSource = ms;
            image.EndInit();
            return image;
        }
    }
}
12
HockeyJ

Je ne pense pas que ImageSourceConverter convertira à partir d'un System.Drawing.Bitmap. Cependant, vous pouvez utiliser les éléments suivants:

public static BitmapSource CreateBitmapSourceFromGdiBitmap(Bitmap bitmap)
{
    if (bitmap == null)
        throw new ArgumentNullException("bitmap");

    var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

    var bitmapData = bitmap.LockBits(
        rect,
        ImageLockMode.ReadWrite,
        PixelFormat.Format32bppArgb);

    try
    {
        var size = (rect.Width * rect.Height) * 4;

        return BitmapSource.Create(
            bitmap.Width,
            bitmap.Height,
            bitmap.HorizontalResolution,
            bitmap.VerticalResolution,
            PixelFormats.Bgra32,
            null,
            bitmapData.Scan0,
            size,
            bitmapData.Stride);
    }
    finally
    {
        bitmap.UnlockBits(bitmapData);
    }
}

Cette solution nécessite que l'image source soit au format Bgra32; si vous avez affaire à d'autres formats, vous devrez peut-être ajouter une conversion.

9
Mike Strobel

dethSwatch - Merci pour votre réponse ci-dessus! Cela a énormément aidé! Après l'avoir implémenté, j'obtenais le comportement souhaité, mais j'ai trouvé que j'obtenais un problème de mémoire/handle dans une autre section de mon programme. J'ai changé le code comme suit, le rendant un peu plus détaillé et le problème a disparu. Merci encore!

    [DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool DeleteObject([In] IntPtr hObject);

    public ImageSource ImageSourceForBitmap(Bitmap bmp)
    {
        var handle = bmp.GetHbitmap();
        try
        {
            ImageSource newSource = Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

            DeleteObject(handle);
            return newSource;
        }
        catch (Exception ex)
        {
            DeleteObject(handle);
            return null;
        }
    }
5
user8366267

La solution la plus simple pour moi:

ImageBrush myBrush = new ImageBrush();
var bitmap = System.Drawing.Image.FromFile("pic1.bmp");
Bitmap bitmap = new System.Drawing.Bitmap(image);//it is in the memory now
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),IntPtr.Zero,Int32Rect.Empty,BitmapSizeOptions.FromEmptyOptions());
myBrush.ImageSource = bitmapSource;
cover.MainGrid.Background = myBrush;
cover.Show();
bitmap.Dispose();
1
vinsa