68 votes

Conversion de BitmapImage en Bitmap et vice versa

J'ai BitmapImage en C#. J'ai besoin de faire des opérations sur l'image. Par exemple, mise en niveaux de gris, ajout de texte sur l'image, etc.

J'ai trouvé une fonction dans stackoverflow pour l'échelle de gris qui accepte Bitmap et renvoie Bitmap.

Je dois donc convertir BitmapImage en Bitmap, effectuer une opération et reconvertir.

Comment puis-je faire ceci? Est-ce le meilleur moyen ?

93voto

Sascha Hennig Points 1592

Il n'est pas nécessaire d'utiliser des bibliothèques étrangères.

Convertir une BitmapImage en Bitmap :

 private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
    // BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));

    using(MemoryStream outStream = new MemoryStream())
    {
        BitmapEncoder enc = new BmpBitmapEncoder();
        enc.Frames.Add(BitmapFrame.Create(bitmapImage));
        enc.Save(outStream);
        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);

        return new Bitmap(bitmap);
    }
}

Pour reconvertir le Bitmap en BitmapImage :

 [System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

private BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
{
    IntPtr hBitmap = bitmap.GetHbitmap();
    BitmapImage retval;

    try
    {
        retval = (BitmapImage)Imaging.CreateBitmapSourceFromHBitmap(
                     hBitmap,
                     IntPtr.Zero,
                     Int32Rect.Empty,
                     BitmapSizeOptions.FromEmptyOptions());
    }
    finally
    {
        DeleteObject(hBitmap);
    }

    return retval;
}

49voto

LawMan Points 123

Voici une méthode d'extension pour convertir un Bitmap en BitmapImage.

     public static BitmapImage ToBitmapImage(this Bitmap bitmap)
    {
        using (var memory = new MemoryStream())
        {
            bitmap.Save(memory, ImageFormat.Png);
            memory.Position = 0;

            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
            bitmapImage.Freeze();

            return bitmapImage;
        }
    }

9voto

C0bra5 Points 91

Si vous avez juste besoin de passer de BitmapImage à Bitmap c'est assez simple,

 private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
    {
        return new Bitmap(bitmapImage.StreamSource);
    }

4voto

en utilisant System.Windows.Interop; ...

  private BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
        {                
            BitmapSource i = Imaging.CreateBitmapSourceFromHBitmap(
                           bitmap.GetHbitmap(),
                           IntPtr.Zero,
                           Int32Rect.Empty,
                           BitmapSizeOptions.FromEmptyOptions());
            return (BitmapImage)i;
        }

3voto

Wolfshead Points 21

Je viens d'essayer d'utiliser ce qui précède dans mon code et je pense qu'il y a un problème avec la fonction Bitmap2BitmapImage (et peut-être l'autre aussi).

 using (MemoryStream ms = new MemoryStream())

La ligne ci-dessus entraîne-t-elle l'élimination du flux ? Ce qui signifie que le BitmapImage renvoyé perd son contenu.

Comme je suis un débutant WPF, je ne suis pas sûr que ce soit la bonne explication technique, mais le code n'a pas fonctionné dans mon application jusqu'à ce que j'aie supprimé la directive using.

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X