IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Windows Presentation Foundation Discussion :

Convertir BitmapImage en tableau de byte en wpf


Sujet :

Windows Presentation Foundation

  1. #1
    Invité
    Invité(e)
    Par défaut Convertir BitmapImage en tableau de byte en wpf
    Bonjour et joyeux noël à vous les développeurs.

    Mes problèmes ne finissent jamais surtout quand tu es debutant.bon j'ai enregistré une image en tableau de byte dans une BD dont le champs en question de type varbinary.ensuite je recuperé ce tableau de byte depuis la BD que j'ai converti en BitmapImage pour l'attribuer à la propriété Source de mon controle Image.Ce que je souhaite faire est de convertir cette fois la le BitmapImage en tableau de byte.J'ai lu beaucoup d'exemples mais ce sont des exemple en winform pas en WPF.

    Si quelqu'un a une idée.Merci

  2. #2
    Membre du Club
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2011
    Messages
    50
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2011
    Messages : 50
    Points : 68
    Points
    68
    Par défaut
    bonjour,

    voici ce que tu cherches :

    http://social.msdn.microsoft.com/For...ersa?forum=wpf
    Vous avez la réponse à votre question ? Mettez votre sujet en

    Une personne vous a correctement aidé ? Cliquez sur le +1

  3. #3
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    Rebonjour et bonne fete à tous....

    Pour recuper un tableau de pixels de l'image affichee dans un control image(ou une partie d'image sous forme de tableau de pixels) ,tu passes par un BitmapSource :

    code xaml winform:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
     
    <Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
            Loaded="Window_Loaded" >
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition ></RowDefinition>
                <RowDefinition ></RowDefinition>
                </Grid.RowDefinitions>
            <Image 
                Margin="5"
                x:Name="Img"
                Width="200"
                Source="Resources/Nenuphars.jpg"   >
            </Image>
            <Image 
                Grid.Row="1"
                Margin="5"
                x:Name="ImgModified"
                Width="200">
            </Image>
        </Grid>
    </Window>
    code behind .vb du winform
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
     
    Class MainWindow 
        Dim myBmp As BitmapSource
     
        Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
            'RECUPERE LE BitmapSource DU  CONTROL Img
     
            myBmp = CType(Me.Img.Source, BitmapSource)
            Dim w As Integer = myBmp.PixelWidth
            Dim h As Integer = myBmp.Height
     
            Dim stride As Integer = myBmp.Format.BitsPerPixel * w
            Dim nbPixel As Integer = stride * h
            Dim arrPixels() As Byte = New Byte(nbPixel) {}
     
            'COPIE TOUTE L'IMAGE DANS => arrPixels
            myBmp.CopyPixels(arrPixels, stride, 0)
     
     
     
            'COPIE ZONE D'IMAGE DANS => zonePixels
     
            Dim srcRect As Int32Rect = New Int32Rect(100, 100, 300, 300)
     
            Dim zonePixels(stride * srcRect.Height) As Byte
            myBmp.CopyPixels(srcRect, zonePixels, stride, 0)
     
            'CREE UN BitmapSource DE LA ZONE SPECIFIE ET L'AFFICHE DANS CONTROL ImgModified.
            Dim tempBmpSource As BitmapSource = BitmapSource.Create(
                srcRect.Width, srcRect.Height,
                myBmp.DpiX, myBmp.DpiY,
                myBmp.Format, Nothing,
                zonePixels, stride)
            Me.ImgModified.Source = tempBmpSource
        End Sub
    End Class
    bon code...

  4. #4
    Invité
    Invité(e)
    Par défaut
    bonjour,le VB c'est une peu compliqué pour moi.la source de
    mon controle Image est de type BitmapImage

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    <Image Source="{Binding MonImage}"/>
    MonImage est une propriété de type BitmapImage provenant d'une Class.

    J'ai trouvé cette classe dans mes recherche mais je ne sais pas comment l'utiliser.De plus il me semble que le methode ConvertBack() n'est pas totalement achevée.Si quelqu'un qui à deja utiliser pourrait me m'aider.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
     
     
      [ValueConversion(typeof(byte[]), typeof(ImageSource))]
        public class ByteArrayToImageSource : IValueConverter
        {
            #region Implementation of IValueConverter
     
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                var byteArrayImage = value as byte[];
     
                if (byteArrayImage != null && byteArrayImage.Length > 0)
                {
                    var ms = new MemoryStream(byteArrayImage);
     
                    var bitmapImg = new BitmapImage();
     
                    bitmapImg.BeginInit();
                    bitmapImg.StreamSource = ms;
                    bitmapImg.EndInit();
     
                    return bitmapImg;
                }
     
                return null;
            }
     
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return null;
            }
     
            #endregion
        }

  5. #5
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    re
    Ton besoin n'ayant pas ete explicite au depart et sans code j'ai donne du vb...Tout post sans code c'est pour moi du blahblah n'est-ce pas !...


    Cela ne change rien au probleme....
    Les problemes souleves par l'utilisation du BitmapImage sont les suivants:
    1er Probleme:
    -on serait tente de vouloir recuperer le stream de bytes à partir de bitmapiimage.streamsource comme ceci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    BitmapImage bi = this.FindResource("bi") as BitmapImage;
                Stream ms = (Stream)bi.StreamSource;
     
                byte[] buffer=new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, (int)ms.Length-1 );
                ms.Close();
    Helas si le BitmapImage est lu à partir d'un Uri ,le StreamSource est vide...!!!
    2eme Probleme:
    -un buffer de pixels cree avec les versions static de BitmapSource.Create()
    ou de BitmapImage.Create() ou les versions d'intances :mybmp.CopyPixels()
    ou mybi.CopyPixels() n'est pas reconnu par BitmapImage...car il n'as pas le format appropriee...



    La solution est un moyen detourne :
    - recuperer le Frame d'image store dans Image.Source
    - utiliser un Encoder pour populer un MemoryStream
    - sauver le MemoryStream
    - soit l'affecter le MemoryStream au StreamSource du BitmapImage
    - soit (whatever you want) l'affecter à un buffer de pixels...

    code xaml:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
     
    <Window x:Class="WpfImageToBytesPixel.Window1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Window1" Height="300" Width="300"
            Loaded="Window_Loaded">
        <Window.Resources>
            <BitmapImage x:Key="bi"
                         CacheOption="OnLoad"
                         CreateOptions="PreservePixelFormat"
                         UriSource="Resources/Nenuphars.jpg">
            </BitmapImage>
        </Window.Resources>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
                <RowDefinition Height="auto"></RowDefinition>
            </Grid.RowDefinitions>
            <Image 
                Grid.Row="0"
                Margin="5"
                x:Name="originalImg"
                Source="{Binding Source={StaticResource bi},Path=UriSource}"   
               >
            </Image>
     
            <StackPanel  Grid.Row="1" Orientation="Horizontal" >
                <Image 
                Grid.Row="1"
                Margin="5"
                x:Name="imgFromFrame"
              >
                </Image>
                <Image 
                    Grid.Row="1"
                    Margin="5"
                    x:Name="imgFromByte"
                  >
                </Image>
            </StackPanel >
            <StackPanel  Grid.Row="2" Orientation="Horizontal" >
                <Button  
                    Margin="5"
                    x:Name="btnSaveImage"
                    Content="Save Image"     
                    Width="100"
                    Click="btnSaveImage_Click"      />
                <TextBlock 
                    Margin="5"
                    x:Name="tb"
                    FontSize="14">
     
                </TextBlock>
            </StackPanel>
     
        </Grid>
    </Window>
    code behind .cs du winform:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    using System.IO;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Net;
    using System.Threading.Tasks;
     
    namespace WpfImageToBytesPixel
    {
        /// <summary>
        /// Logique d'interaction pour Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
            BitmapImage bi;
     
            public Window1()
            {
                InitializeComponent();
            }
     
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                BitmapFrame frame = (BitmapFrame)this.originalImg.Source;
     
                MemoryStream ms = new MemoryStream();
                BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(frame));
                encoder.Save(ms);
     
                //AFFICHAGE DU Frame
                this.imgFromFrame.Source = encoder.Frames[0];
     
                //AFFICHE DU MemoryStream
                bi = new BitmapImage();
                bi.BeginInit();
                ms.Position = 0;// TRES TRES IMPORTANT CECI ...!!!
                bi.CacheOption = BitmapCacheOption.OnLoad; //Mise en cached memoire
                bi.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                bi.StreamSource = ms;
                bi.EndInit();
     
     
                this.imgFromByte.Source = bi;
     
     
                //  WHATEVER YOU WANT : storage dans un buffer pixels
                byte[] buffer = new byte[ms.Length];
                ms.Position = 0; 
                ms.Read(buffer, 0, (int)ms.Length - 1);
     
     
                //Libere Ressources
                ms.Close();
                encoder = null;
                tb.Text = "nb bytes lus :" + buffer.Length;
     
            }
            //  Save en format PNG de l'image modifie... 
            string appPath = Directory.GetCurrentDirectory() + @"\";
            private void btnSaveImage_Click(object sender, RoutedEventArgs e)
            {
                if (bi != null)
                {
                    // Encode tempBmp comme  PNG .
                    PngBitmapEncoder png = new PngBitmapEncoder();
                    png.Frames.Add(BitmapFrame.Create(bi));
                    using (Stream stm = File.Create(appPath + "new.png"))
                    {
                        png.Save(stm);
                    }
     
                }
     
     
     
     
            }
     
     
     
     
            public Byte[] ImageToByte(BitmapImage imageSource)
            {
                Stream stream = imageSource.StreamSource;
                stream.Position = 0;
                Byte[] buffer = null;
                if (stream != null && stream.Length > 0)
                {
                    using (BinaryReader br = new BinaryReader(stream))
                    {
                        buffer = br.ReadBytes((Int32)stream.Length);
                    }
                }
     
                return buffer;
            }
     
        }
    }
    bon code....

  6. #6
    Invité
    Invité(e)
    Par défaut
    Bonjour,
    merci pour le code je vais essayer cela.

  7. #7
    Membre du Club
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    66
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 66
    Points : 42
    Points
    42
    Par défaut
    Bonjour,

    As-tu réussi? moi j'essaye en wpf avec du vb.net et je galére un peu
    ce qui ne te tue pas te rend plus fort

  8. #8
    Invité
    Invité(e)
    Par défaut
    Bonjour,
    en fait j'ai pas vraiment réussi à converti BitmapImage en Byte mais je suis simplement contenté de l'inverse c'est-à-dire Byte en BitmapImageen utilisant la methode Convert.

  9. #9
    Membre du Club
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    66
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 66
    Points : 42
    Points
    42
    Par défaut
    J'ai converti le code de Mabrouki et en jouant un peu avec, j'ai réussi a obtenir ce que je voulais, notamment avec le buffer().

    Maintenant je m'amuse à le travailler un peu pour mieux comprendre le fonctionnement et aller plus loin
    ce qui ne te tue pas te rend plus fort

  10. #10
    Invité
    Invité(e)
    Par défaut
    c'est vraiment cool mais peux-tu partager le code pour moi ainsi d'autres personnes qui seront confrontés à ce genre de problème?

  11. #11
    Membre du Club
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    66
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 66
    Points : 42
    Points
    42
    Par défaut
    En fait je reprends quasi que le code de mabrouki, mais pour vérifier une partie du fonctionnement je copie le buffer dans un second que je modifie et affiche

    code VB.net :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
     Private Sub bntCapture_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
            imgCapture.Source = imgVideo.Source
            Dim frame As BitmapFrame
            ' = DirectCast(Me.imgCapture.Source, BitmapFrame)
            frame = BitmapFrame.Create(imgCapture.Source)
     
            Dim ms As New MemoryStream()
            Dim encoder As New BmpBitmapEncoder()
            encoder.Frames.Add(BitmapFrame.Create(frame))
            encoder.Save(ms)
     
     
            bi = New BitmapImage()
     
            Dim buffer As Byte() = New Byte(ms.Length - 1) {}
            ms.Position = 0
            ms.Read(buffer, 0, CInt(ms.Length) - 1)
     
            'test  buffer modifié mis dans image
            Dim buffer2 As Byte() = New Byte(ms.Length - 1) {}
            buffer2 = buffer
     
            Dim a As Long = 76853
            Do While a < 154000
                buffer2(a) = 0
                a = a + 4
     
            Loop
     
     
            MsgBox(buffer.Length)
            ms.Position = 0
            ms.Write(buffer2, 0, CInt(ms.Length) - 1)
            bi.BeginInit()
            ms.Position = 0
            ' TRES TRES IMPORTANT CECI ...!!!
            bi.CacheOption = BitmapCacheOption.OnLoad
            'Mise en cached memoire
            bi.CreateOptions = BitmapCreateOptions.PreservePixelFormat
            bi.StreamSource = ms
            bi.EndInit()
     
            Me.imgFromByte.Source = bi
     
            'Libere Ressources
            ms.Close()
            encoder = Nothing
            webcam.Stop()
        End Sub
    ce qui ne te tue pas te rend plus fort

Discussions similaires

  1. WordRec Convertir Word en Tableau de Byte
    Par Vilukariok dans le forum Langage
    Réponses: 6
    Dernier message: 20/09/2011, 14h37
  2. convertir object en tableau de byte et inversement
    Par wolfazer dans le forum VB.NET
    Réponses: 5
    Dernier message: 27/11/2008, 10h39
  3. convertir string en tableau de byte
    Par wolfazer dans le forum VB.NET
    Réponses: 3
    Dernier message: 29/10/2007, 08h15
  4. [C#] Convertir un tableau de byte en Image
    Par goulhasch dans le forum ASP.NET
    Réponses: 4
    Dernier message: 24/01/2005, 10h12

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo