如何创建一个包含实像字节数组? [英] How to create a Byte array that contains a real Image?

查看:153
本文介绍了如何创建一个包含实像字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见下面我的代码。



我想创建一个数据的字节数组,我可以转换成实像。当我尝试运行此代码,我得到一个ArgumentException。我需要什么在做For循环,以创造一个合法的字节数组将持有的图像的数据?我不想用一个真实的形象,将其转换为字节数组,我想创建一个形象的形式随机数。




 随机RND =新的随机(); 

公共主窗口()
{
的InitializeComponent();
}

私人无效Button_Click_1(对象发件人,RoutedEventArgs E)
{
字节[] =的ByteArray新的字节[1000];

的for(int i = 0; I< 1000;我++)
{
的ByteArray [I] = Convert.ToByte(Rnd.Next(9));
}
ImageConverter转换器=新ImageConverter();
的BitmapImage形象=(的BitmapImage)Convertor.ConvertFrom(字节阵列);
MyImage.Source =图像;
}




请注意,我不希望同类型的WinForms或类似System.Drawing中/位图的图书馆合作 - 我只希望使用WPF技术。


解决方案

这是你正在寻找,只使用WPF技术的解决方案。



请注意,在步幅参数计算中使用16的恒定值直接从事实,我使用的是16位的像素格式来了。

 私人无效Button_Click_1(对象发件人,RoutedEventArgs E)
{
随机RND =新的随机();

字节[] =的ByteArray新的字节[(INT)MyImage.Width *(INT)MyImage.Height * 3]。

rnd.NextBytes(字节阵列);

变种图像= BitmapSource.Create((int)的MyImage.Width,(INT)MyImage.Height,72,72,
PixelFormats.Bgr565,空字节数组,(4 *(( INT)MyImage.Width * 16 + 31)/ 32));

MyImage.Source =图像;
}


Please see my code below.

I want to create a Byte array with data that I can convert into a real image. When I try to run this code I get an argumentException. What do I need to do in the For loop in order to create a legitimate Byte array that will hold data of an image? I don't want to use a real image and convert it to byte array, I want to create an image form random numbers.

    Random Rnd = new Random();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        Byte[] ByteArray = new Byte[1000];

        for (int i = 0; i < 1000; i++)
        {
            ByteArray[i] = Convert.ToByte(Rnd.Next(9));                
        }
        ImageConverter Convertor = new ImageConverter();
        BitmapImage image = (BitmapImage)Convertor.ConvertFrom(ByteArray);
        MyImage.Source = image;
    }

Notice please that I don't want to work with WinForms types or libraries like system.drawing / bitmap - I only want to use WPF technology.

解决方案

This is the solution you are looking for, using only WPF technology.

Note that the constant value of 16 used in the stride parameter calculation comes directly from the fact that I am using a 16-bit pixel format.

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        Random rnd = new Random();

        Byte[] ByteArray = new Byte[(int)MyImage.Width * (int)MyImage.Height * 3];

        rnd.NextBytes(ByteArray);

        var image = BitmapSource.Create((int) MyImage.Width, (int) MyImage.Height, 72, 72,
            PixelFormats.Bgr565, null, ByteArray, (4*((int)MyImage.Width * 16 + 31)/32));

        MyImage.Source = image;
    }

这篇关于如何创建一个包含实像字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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