I'm currently making a windows forms application in whitch i must implement loading image from .txt (where bytes are written) and to save image as .txt file. Here are my methods:
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();
}
}
When I try to read a .txt file, there is a "parameter not valid" exception from :Image returnImage = System.Drawing.Image.FromStream(ms);