1

I just want to save an image bmp for my screen to a memory stream gut I get:

value cannot be null. parameter name encoder

I use this code

pmb = new Bitmap(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
gc = Graphics.FromImage(pmb);
gc.CopyFromScreen(0, 0, 0, 0, new Size(pmb.Width, pmb.Height));
pb.Image = pmb;
pb.SizeMode = PictureBoxSizeMode.StretchImage;

try
{
    client = new TcpClient(mm.Text, 1430);
    ms = new MemoryStream();
    pb.Image.Save(ms, pb.Image.RawFormat);
    ms.Close();
    byte[] buffer = ms.GetBuffer();
    ns = client.GetStream();
    br = new BinaryWriter(ns);
    br.Write(buffer);
    br.Close();
    ns.Close();
    client.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
1
  • Please debug your code and specify line where it throws (I'd be surprised if it is anywhere from this code). Commented Oct 5, 2015 at 23:00

2 Answers 2

2

You are accessing your MemoryStream after you close it

ms.Close();
byte[] buffer = ms.GetBuffer();

Also, if an Exception is ever thrown, you will not clean up resources. Make use of the using keyword for everything that implements IDisposable.

You need to rewind the memory stream after writing to it and before saving it out

ms.Seek(0, SeekOrigin.Begin);
Sign up to request clarification or add additional context in comments.

13 Comments

same i change the code ms.Close(); byte[] buffer = ms.GetBuffer();
@alexmike Changed it to what?
i searched in google maybe the problem of image format
@alexmike why are you using GetBuffer? ToArray is probably more suitable if you don't know what you are doing.
@EricJ. msdn.microsoft.com/en-us/library/…: "This method works when the memory stream is closed." (same for ToArray).
|
-1

It is save memory

MemoryStream ms = new MemoryStream();
pictureBox_ad_cam_in.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
kanvert = Convert.ToBase64String(ms.ToArray());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.