C#WPF XAML-将ImageSource从字节转换为字节[]并显示 [英] C# WPF XAML - Convert ImageSource from/to byte[] and display

查看:89
本文介绍了C#WPF XAML-将ImageSource从字节转换为字节[]并显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我知道互联网上有很多主题都在谈论这个,但是我找不到解决问题的答案.

我想将ImageSource与byte []数组进行相互转换.

不是位图,图像或其他.我希望将ImageSource放在XAML的图片"标记中.

现在,我尝试将byte []转换为ImageSource.

我的XAML包含在一个TextBox中,其中包含Bytes和Image,目前为空.当我按一个按钮时,我希望从TextBox计算图像并显示.

我的CodeBehind是:

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 :

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 :

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;
        }
    }



biImg.EndInit()上的一例.



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...

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.

推荐答案

您的文本框包含Base64(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);


这是base64编码的图像.要获取实际的图像字节,您需要:
This is base64 encoded image. To get actual image bytes you need:
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);
    }
}


我在这里发布了我拥有的所有解决方案(在您的帮助下:))

XAML:
I Post here the entire solution I have (with your help :) )

XAML :
<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



MainWindow.cs

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#转换类:



C# Convert Class :

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 :)


这篇关于C#WPF XAML-将ImageSource从字节转换为字节[]并显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆