Click here to Skip to main content
11,641,659 members (60,375 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C#4.0
I need to save image but i got error.How to solved this error?
byte[] pic = new byte[1];
                pic[0] = 0;
                if (pcbPhoto.Image != null)
                    stream = new MemoryStream();
                    pcbPhoto.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);// error occur here...
                    pic = stream.ToArray();
error : A generic error occurred in GDI+.

Posted 26-Sep-12 21:44pm
Edited 26-Sep-12 21:50pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Normally, this error occurs because the output stream is in use when you try to save, but since you are outputting to a MemoryStream that is not the case.

Sorry, but the problem is not in teh code you show - it's a lot further back...

The problem is probably that the stream you used to create the image in the first place is no longer available - it has been closed or disposed by the time you get to the Save method. And that doesn't work!
Try this:
When you load the image in the first place, create a new image as a copy of the actual picture, and use that - you can dispose of the original version you read in. For example:
Image myImage;
using (Image inputImage = Image.FromFile(@"D:\Temp\MyPic.jpg"))
    myImage = new Bitmap(inputImage);
Because the new image is not associated with a file or stream, it can be saved with no problem.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Use this code to read picture as Bytes array

MemoryStream stream=new MemoryStream();
            byte[] pic=stream.ToArray();

then insert pic into the database
        SqlConnection con = new SqlConnection
                               ("Data Source=localhost;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=123456");
            SqlCommand com = new SqlCommand("insert into Employees(LastName,FirstName,Photo) values('aaaa','bbb',@Photo)", con);
   com.Parameters.AddWithValue("@Photo", pic);

Hope this helps you,

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

  Print Answers RSS
0 Mika Wendelius 260
1 DamithSL 248
2 Afzaal Ahmad Zeeshan 129
3 OriginalGriff 120
4 Sergey Alexandrovich Kryukov 80
0 Mika Wendelius 460
1 OriginalGriff 265
2 DamithSL 258
3 CPallini 169
4 Afzaal Ahmad Zeeshan 149

Advertise | Privacy | Mobile
Web02 | 2.8.150731.1 | Last Updated 27 Sep 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100