0

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

WayofYore
  • 3
  • 1
  • let me know if its not solving your purpose... – Pranay Rana Mar 17 '18 at 14:19
  • Your `ByteToImage` function can cause problems. [An Image object created from a stream will need the stream to remain open for the entire life cycle of the image object.](https://msdn.microsoft.com/en-us/library/z7ha67kw(v=vs.110).aspx#Anchor_2) – Nyerguds Mar 21 '18 at 23:00

0 Answers0