Click here to Skip to main content
15,888,579 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I tried to convert the picturebox image to byte array, but system throwing above error.

I have given my code below.

C#
byte[] fileBytes = null;

MemoryStream memoryStream = new MemoryStream();
                pictureBoxAssets.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                fileBytes = memoryStream.ToArray();

memoryStream.Dispose();


Thanks in advance.
Posted

Your MemoryStream instance contains no data (see the documentation[^]).
 
Share this answer
 
Comments
Sarath kumar.N 28-May-15 5:13am    
Can u rewrite my code?
Since you are writing into the memory stream, and get the error there implies that the error is actually a fair way away from this point. Have a look at where you load the Image - if the original stream you loaded the image from is not still open, then you will get this error - it's in the documentation for Image.FromStream[^] tyhat the stream must remain open for teh life of the Image.

Similarly, if you use Image.FromFile, the source file will be locked for the life of the image.

One way to get round this is to load the Image, draw it into a new Bitmap object and then dispose the original and use the copy.
 
Share this answer
 
Comments
Sarath kumar.N 28-May-15 5:25am    
Could you rewrite my code?
OriginalGriff 28-May-15 5:38am    
Read what I said, please: "Have a look at where you load the Image"
Since you don't show that, I couldn't rewrite it even if I wanted to...

Tell me, is there any point in asking for help if you don't read the help you are given?
Sarath kumar.N 28-May-15 5:57am    
Sorry for my fault. Actually, the image is already in picturebox. I just need to convert that image into byte array. Thanks.
OriginalGriff 28-May-15 6:00am    
Read what I said: it's *how* you load the picture into the picturebox that causes the problem...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900