C#将字节数组转换为图像,将图像转换为数组 - stream参数无效

时间:2018-03-17 14:14:43

标签: c# image parameters stream type-conversion

我目前正在制作一个Windows窗体应用程序,我必须实现从.txt(其中写入字节)加载图像并将图像保存为.txt文件。 以下是我的方法:

struct [[nodiscard]] error_info { /* ... */ };
error_info &foo();
void f() { foo(); } // warning not encouraged: not a nodiscard call, because neither
                    // the (reference) return type nor the function is declared nodiscard

当我尝试读取.txt文件时,有一个"参数无效"例外情况: public static Image ByteToImage(byte[] byteArrayIn) { using (MemoryStream ms = new MemoryStream(byteArrayIn, 0, byteArrayIn.Length)) { ms.Seek(0, SeekOrigin.Begin); Image returnImage = System.Drawing.Image.FromStream(ms); return returnImage; } } private void button3_Click(object sender, EventArgs e) { if (byteArr != null) { pictureBox1.Image = ByteToImage(byteArr); } } private void button4_Click(object sender, EventArgs e) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); IntPtr ptr = bmpData.Scan0; // adres pierwszej linii int bytes = Math.Abs(bmpData.Stride) * bmp.Height; byte[] values = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, values, 0, bytes); File.WriteAllBytes("file.txt", values); } private void ReadBytearrToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog open_file = new OpenFileDialog(); open_file.ShowDialog(); string path = open_file.FileName; if (File.Exists(path)) { FileStream fs = new System.IO.FileStream(path, FileMode.Open); byteArr = new byte[fs.Length]; fs.Position = 0; fs.Read(byteArr, 0, (int)(fs.Length)); fs.Close(); } }

0 个答案:

没有答案