Click here to Skip to main content
15,889,931 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Hi,
I know a lot of subjects on the internet talk about this but I don't find an answer for my problem.

I want to convert ImageSource to and from byte[] array.

Not Bitmap, Image or others. I want an ImageSource to put in after in a XAML 'Image' tag.

For now, I try to convert a byte[] to ImageSource.

My XAML consist in a TextBox contain the Bytes and a Image, empty for now. When i push a button, i want the Image calculated from TextBox and show.

My CodeBehind is :
C#
public partial class MainWindow : DXWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            btnChargerImage.Click += new RoutedEventHandler(btnChargerImage_Click);
        }

        void btnChargerImage_Click(object sender, RoutedEventArgs e)
        {
            if (tbBytes.Text != String.Empty)
            {
                // Convert my TextBox in a byte array
                byte[] imgStr = new byte[tbBytes.Text.Length];
                for (int i = 0; i < tbBytes.Text.Length; i++)
                {
                    imgStr[i] = (byte)tbBytes.Text[i];
                }
                imgImage.Source = ByteImageConverter.ByteToImage(imgStr);
            }
        }
    }


My class for convert :
C#
public class ByteImageConverter
    {
        public static ImageSource ByteToImage(byte[] imageData)
        {
            BitmapImage biImg = new BitmapImage();
            MemoryStream ms = new MemoryStream(imageData);
            biImg.BeginInit();
            biImg.StreamSource = ms;
            biImg.EndInit();

            ImageSource imgSrc = biImg as ImageSource;

            return imgSrc;
        }
    }


An exeption on biImg.EndInit() is done.

{"Impossible de trouver un composant d'image adapté pour terminer l'opération."}

so in english, i mean it's like :

{"Unable to find a suitable image component to finish operation."}


I don't understand why and of course what I need to do to convert this...

A tutor give me this class to do it (it work) but I do not use (i tried)
and of course I don't understand how it work and how to make the back conversion...

C#
namespace ContactManager.Tools.Converters
{
    [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
    }
}


Thanks by advance and sorry for my bad english :)

If you need more explains, tell me, i'll try to explain the best I can.
Posted
Updated 25-Sep-12 2:22am
v4
Comments
sjelen 25-Sep-12 9:26am    
And what do you put in TextBox?
Is it hexadecimal string representation of image, or base64 encoded image, or something else?
Saesee 25-Sep-12 9:47am    
It's a long text (45160 characters) represent the image.

I have put it in a web page to show you. You can see it at : http://signature.freresdekor.fr/imgcsharp

You text box contains the Base64(http://signature.freresdekor.fr/imgcsharp[^]) representation of the image.

What you can do it take the entire text from the textbox, covert them to byte array using the below code and pass it to your converter.

byte[] imgStr = Convert.FromBase64String(Base64String);
 
Share this answer
 
This is base64 encoded image. To get actual image bytes you need:
C#
void btnChargerImage_Click(object sender, RoutedEventArgs e)
{
    if (tbBytes.Text != String.Empty)
    {
        // Convert my TextBox in a byte array
        //byte[] imgStr = new byte[tbBytes.Text.Length];
        byte[] imgStr = Convert.FromBase64String(tbBytes.Text);

        for (int i = 0; i < tbBytes.Text.Length; i++)
        {
            imgStr[i] = (byte)tbBytes.Text[i];
        }
        imgImage.Source = ByteImageConverter.ByteToImage(imgStr);
    }
}
 
Share this answer
 
Comments
Saesee 25-Sep-12 10:17am    
@sjelen : Thanks, i'll progress.

With this code, a new error is born.

Line : imgStr[i] = (byte)tbBytes.Text[i];

Error : Exception IndexOutOfRangeException
Index out of limits of array

(it's a traduction)
sjelen 25-Sep-12 10:55am    
Sorry, forgot to delete the loop :)
Saesee 25-Sep-12 10:57am    
no problem :p I try now to convert an Image from the OpenFileDialog but for now i haven't create the method for doing it because I don't know how to do. (maybe withe Stream or something I have read on forums...)
Ashraff Ali Wahab 25-Sep-12 10:17am    
Remove the for loop:)
Saesee 25-Sep-12 10:32am    
Exact :)

It's ok now for Base64 to Image. I now try the Image loaded from OpenDialog to Base64 ^^

for byte[] to ImageSource :
void btnChargerImage_Click(object sender, RoutedEventArgs e)
{
if (tbBytes.Text != String.Empty)
{
// Convert my TextBox in a byte array
byte[] imgStr = Convert.FromBase64String(tbBytes.Text);
imgImage.Source = ByteImageConverter.ByteToImage(imgStr);
}
}
I Post here the entire solution I have (with your help :) )

XAML :
XML
<grid>>
    <Button x:Name="btnOuvrirImage" Content="Image --> Base64" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="130"/>
    <Button x:Name="btnChargerImage" Content="Base64 --> Image" HorizontalAlignment="Left" Margin="150,10,0,0" VerticalAlignment="Top" Width="130"/>
    <Image x:Name="imgImage" Margin="290,10,10,10"/>
    <TextBox x:Name="tbBytes" Margin="10,42,0,10" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" HorizontalAlignment="Left" Width="270"/>
</Grid>


MainWindow.cs
C#
public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            btnChargerImage.Click += new RoutedEventHandler(btnChargerImage_Click);
            btnOuvrirImage.Click += new RoutedEventHandler(btnOuvrirImage_Click);
        }

        void btnChargerImage_Click(object sender, RoutedEventArgs e)
        {
            if (tbBytes.Text != null && tbBytes.Text.Length > 0)
            {
                // Convert TextBox in a Byte array
                byte[] imgStr = Convert.FromBase64String(tbBytes.Text);
                imgImage.Source = ByteImageConverter.ByteToImage(imgStr);
            }
        }

        void btnOuvrirImage_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofg = new OpenFileDialog();
            ofg.Title = "Select an image";
            ofg.Filter = "Images (.jpg, .png, .gif, .bmp)|*.jpg;*.png;*.gif;*.bmp";
            ofg.Multiselect = false;

            if (ofg.ShowDialog() == true)
            {
                if (ofg.FileName != null && ofg.FileName.Length > 0)
                {
                    ofg.OpenFile();
                    FileStream fs = new FileStream(ofg.FileName, FileMode.Open, FileAccess.Read);
                    tbBytes.Text = ByteImageConverter.ImageToByte(fs);

                    byte[] imgStr = Convert.FromBase64String(tbBytes.Text);
                    imgImage.Source = ByteImageConverter.ByteToImage(imgStr);
                }
            }
        }
    }


C# Convert Class :
C#
public class ByteImageConverter
    {
        public static ImageSource ByteToImage(byte[] imageData)
        {
            BitmapImage biImg = new BitmapImage();
            MemoryStream ms = new MemoryStream(imageData);
            biImg.BeginInit();
            biImg.StreamSource = ms;
            biImg.EndInit();

            ImageSource imgSrc = biImg as ImageSource;

            return imgSrc;
        }

        public static string ImageToByte(FileStream fs)
        {
            byte[] imgBytes = new byte[fs.Length];
            fs.Read(imgBytes, 0, Convert.ToInt32(fs.Length));
            string encodeData = Convert.ToBase64String(imgBytes, Base64FormattingOptions.InsertLineBreaks);
            
            return encodeData;
        }
    }


Hop will helpful for others like me :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900