Click here to Skip to main content
12,821,670 members (41,826 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# 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 22:44pm
Updated 26-Sep-12 22: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
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170308.1 | Last Updated 27 Sep 2012
Copyright © CodeProject, 1999-2017
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