简体   繁体   English

C#字节数组不能使用相同的字节数组

[英]C# byte array to image not working with identical byte arrays

The complete code 完整的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Display byte array as image
        private void button1_Click(object sender, EventArgs e)
        {
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            Image img = ByteArrayToImage(File.ReadAllBytes("")); //fill with path info

            pictureBox1.Image = (Image)img.Clone();
        }

        //Convert to image from bytes
        public Image ByteArrayToImage(byte[] byteArrayIn)
        {
            using (MemoryStream ms = new MemoryStream(byteArrayIn))
            {
                ms.Position = 0;
                Image returnImage = Image.FromStream(ms);
                return returnImage;
            }
        }

        //Open Image for conversion
        private void loadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            DialogResult dr = new DialogResult();
            dr = opf.ShowDialog();
            if (dr == DialogResult.OK)
            {
                pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                pictureBox1.Image = Image.FromFile(opf.FileName);
            }
        }

        private void convertImage_Click(object sender, EventArgs e)
        {
            //Choose Path to Save To
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Title = "Choose Directory and File Name";
            saveDialog.Filter = "Canga Comix *.CCMX|*.CCMX";
            DialogResult dr = saveDialog.ShowDialog();
            if (dr == DialogResult.OK)
            {
                byte[] array;

                //Save Image
                using (MemoryStream ms = new MemoryStream())
                {
                    Image img = pictureBox1.Image;
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    array = ms.ToArray();
                }

                using(FileStream fs = new FileStream(saveDialog.FileName, FileMode.Create))
                {
                    fs.Write(array, 0, array.Length);
                }
            }
        }

        //clear image
        private void clearImage_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = null;
        }
    }
}

These are pretty standard. 这些都很标准。 I have a test program that uses these methods. 我有一个使用这些方法的测试程序。 It opens an image in a pictureBox and then converts it to byte[] and clears the pictureBox Image. 它在pictureBox中打开一个图像,然后将其转换为byte []并清除pictureBox图像。 Then you can hit Load byte[] and it will display the picture properly as it runs the ByteArrayToImage method. 然后你可以点击Load byte [],它会在运行ByteArrayToImage方法时正确显示图片。

Then if I save out a picture from my other program and try to open it in the test program it gives me the unholy "Parameter is not valid" error. 然后,如果我从我的其他程序中保存一张图片并尝试在测试程序中打开它,它会给我一个不圣洁的“参数无效”错误。 Even though both text documents are exactly the same as far as I can tell. 尽管这两个文本文件完全相同,但据我所知。

This code contains a common problem. 此代码包含一个常见问题。 Here you create an Image bound to a stream containing your bitmap... 在这里,你创建一个Image绑定到包含您的位图流...

public Image ByteArrayToImage(byte[] byteArrayIn)
{
    using (MemoryStream ms = new MemoryStream(byteArrayIn))
    {
        ms.Position = 0;
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }
}

... and the using block disposes the MemoryStream instance on the way out, which makes the Image rather useless. ...而using块在出路时配置了MemoryStream实例,这使得Image变得毫无用处。

You can get an Image that manages its own memory instead of expecting your stream to stick around by calling Clone() : 你可以通过调用Clone()获得一个管理自己内存的Image ,而不是期望你的流可以留下来:

public Image ByteArrayToImage(byte[] byteArrayIn)
{
    using (MemoryStream ms = new MemoryStream(byteArrayIn))
    using (Image returnImage = Image.FromStream(ms))
    {
        return returnImage.Clone();
    }
}

The clone isn't bound to the original stream. 克隆未绑定到原始流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM