473,396 Members | 1,975 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Converting image to byte array

Hello,

I am trying to convert a jpeg image stored in a PictureBox to a byte array
in order to later save it to a database, but I get this error : "Generic
Error in GDI+".

The source code is the following (when clicking in a button):

MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); //
<-- Error is here
byte[] data = new byte[ms.Length];
ms.Position = 0;
ms.Read(data, 0, (int)ms.Length);
...save the array to a database

The image inside the PictureBox was obtained from a jpeg file the following
way (when clicking other button and by using a OpenFileDialog in order to
define the source file):

pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);

Is there something I am doing wrong ?. In fact, sometimes the error does not
raise, but when I try to draw an image in some control, the image is not
displayed. It seems that GDI+ was kept in a corrupted state.

Does anyone have any hint ?

Thanks in advance
Luis A.
Nov 17 '05 #1
6 41585
Hi Luis,
I just ran the extact code you had and it compiled and executed perfectly,
I read an image into the byte array. Verify that the images you are trying
to load can be opended in other applications. Was there any more information
along with the exception that was thrown?

Mark.

"Luis Arvayo" wrote:
Hello,

I am trying to convert a jpeg image stored in a PictureBox to a byte array
in order to later save it to a database, but I get this error : "Generic
Error in GDI+".

The source code is the following (when clicking in a button):

MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); //
<-- Error is here
byte[] data = new byte[ms.Length];
ms.Position = 0;
ms.Read(data, 0, (int)ms.Length);
...save the array to a database

The image inside the PictureBox was obtained from a jpeg file the following
way (when clicking other button and by using a OpenFileDialog in order to
define the source file):

pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);

Is there something I am doing wrong ?. In fact, sometimes the error does not
raise, but when I try to draw an image in some control, the image is not
displayed. It seems that GDI+ was kept in a corrupted state.

Does anyone have any hint ?

Thanks in advance
Luis A.

Nov 17 '05 #2
http://www.eggheadcafe.com/PrintSear...asp?LINKID=799

--
2004 and 2005 Microsoft MVP C#
Robbe Morris
http://www.masterado.net

Earn $$$ money answering .NET Framework
messageboard posts at EggHeadCafe.com.
http://www.eggheadcafe.com/forums/merit.asp

"Luis Arvayo" <am**********@prodigy.net.mx> wrote in message
news:eA****************@TK2MSFTNGP10.phx.gbl...
Hello,

I am trying to convert a jpeg image stored in a PictureBox to a byte array
in order to later save it to a database, but I get this error : "Generic
Error in GDI+".

The source code is the following (when clicking in a button):

MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); //
<-- Error is here
byte[] data = new byte[ms.Length];
ms.Position = 0;
ms.Read(data, 0, (int)ms.Length);
..save the array to a database

The image inside the PictureBox was obtained from a jpeg file the
following way (when clicking other button and by using a OpenFileDialog in
order to define the source file):

pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);

Is there something I am doing wrong ?. In fact, sometimes the error does
not raise, but when I try to draw an image in some control, the image is
not displayed. It seems that GDI+ was kept in a corrupted state.

Does anyone have any hint ?

Thanks in advance
Luis A.

Nov 17 '05 #3
Robbe Morris [C# MVP] <in**@eggheadcafe.com> wrote:
http://www.eggheadcafe.com/PrintSear...asp?LINKID=799


I'm not keen on that code, I'm afraid. Calling Close manually rather
than with a using statement means that the stream isn't closed if an
exception is thrown - not a problem for a MemoryStream, but not a good
idea in general.

Then there's the:

try
{
// Stuff
}
catch (Exception e)
{
throw e;
}

What's the point of catching it if you're just going to throw it? All
that does is get rid of potentially useful bits of the stack trace.
Then there's using Image.FromStream - the docs say that you must keep
the stream open while the image is in use, but you close the stream
immediately. You're also giving it a stream which is positioned at the
*end* of the data rather than at the beginning - I believe there should
be:

oStream.Position = 0;

after the call to Write and before the call to Image.FromStream.

(MS naming conventions also suggest using camel casing for parameter
names, but that's just a minor nit-pick.)

Finally - I'm not sure how this helps the OP, who had equivalent code
for the relevant section, namely the call to Image.Save...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #4
Good point on the try/catch block. I didn't pay much
attention to that when I posted the code block awhile ago.

As for the other items, that code (with correct try/catch)
and using works quite well in my production apps. I use
it largely for comitting chart images to and from cache.

I posted it just assuming the original poster might
need to perform both actions.

--
2004 and 2005 Microsoft MVP C#
Robbe Morris
http://www.masterado.net

Earn $$$ money answering .NET Framework
messageboard posts at EggHeadCafe.com.
http://www.eggheadcafe.com/forums/merit.asp

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Robbe Morris [C# MVP] <in**@eggheadcafe.com> wrote:
http://www.eggheadcafe.com/PrintSear...asp?LINKID=799


I'm not keen on that code, I'm afraid. Calling Close manually rather
than with a using statement means that the stream isn't closed if an
exception is thrown - not a problem for a MemoryStream, but not a good
idea in general.

Then there's the:

try
{
// Stuff
}
catch (Exception e)
{
throw e;
}

What's the point of catching it if you're just going to throw it? All
that does is get rid of potentially useful bits of the stack trace.
Then there's using Image.FromStream - the docs say that you must keep
the stream open while the image is in use, but you close the stream
immediately. You're also giving it a stream which is positioned at the
*end* of the data rather than at the beginning - I believe there should
be:

oStream.Position = 0;

after the call to Write and before the call to Image.FromStream.

(MS naming conventions also suggest using camel casing for parameter
names, but that's just a minor nit-pick.)

Finally - I'm not sure how this helps the OP, who had equivalent code
for the relevant section, namely the call to Image.Save...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #5
Robbe Morris [C# MVP] <in**@eggheadcafe.com> wrote:
Good point on the try/catch block. I didn't pay much
attention to that when I posted the code block awhile ago.

As for the other items, that code (with correct try/catch)
and using works quite well in my production apps. I use
it largely for comitting chart images to and from cache.
That doesn't mean it's correct though. I suspect it entirely depends on
what you do with the image. Here's a test method (I've made your
methods static):

static void Main()
{
Image original = Image.FromFile ("test.jpg");
byte[] bytes = ConvertImageToByteArray(original);
Image converted = ConvertByteArrayToImage(bytes);
Image thumb = converted.GetThumbnailImage
(100, 100, null, new IntPtr(0));
}

All is fine until you ask for the thumbnail - at which point things go
wrong, with your code as it currently is. If you don't close the
stream, however, everything's fine. Even if it works for your cases,
doing something which goes against what the documentation specifically
requires seems a bad idea to me.

I'm still surprised that it works without repositioning the stream, but
maybe that's just something it does internally automatically. Bit of a
shame, in a way, as it presumably means you can't have a seekable
stream which contains some other data and *then* the image data..
I posted it just assuming the original poster might
need to perform both actions.


Unfortunately the problem was performing just the one action to start
with :(

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6
I only use ConvertByteArrayToImage in one place and it doesn't really try
to do anything with the image afterwards. Thus, I never saw issues with
this.

That said, I hate to have tips out there that aren't accurate. It is
correct now.

--
2004 and 2005 Microsoft MVP C#
Robbe Morris
http://www.masterado.net
Earn $$$ money answering .NET Framework
messageboard posts at EggHeadCafe.com.
http://www.eggheadcafe.com/forums/merit.asp

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Robbe Morris [C# MVP] <in**@eggheadcafe.com> wrote:
Good point on the try/catch block. I didn't pay much
attention to that when I posted the code block awhile ago.

As for the other items, that code (with correct try/catch)
and using works quite well in my production apps. I use
it largely for comitting chart images to and from cache.


That doesn't mean it's correct though. I suspect it entirely depends on
what you do with the image. Here's a test method (I've made your
methods static):

static void Main()
{
Image original = Image.FromFile ("test.jpg");
byte[] bytes = ConvertImageToByteArray(original);
Image converted = ConvertByteArrayToImage(bytes);
Image thumb = converted.GetThumbnailImage
(100, 100, null, new IntPtr(0));
}

All is fine until you ask for the thumbnail - at which point things go
wrong, with your code as it currently is. If you don't close the
stream, however, everything's fine. Even if it works for your cases,
doing something which goes against what the documentation specifically
requires seems a bad idea to me.

I'm still surprised that it works without repositioning the stream, but
maybe that's just something it does internally automatically. Bit of a
shame, in a way, as it presumably means you can't have a seekable
stream which contains some other data and *then* the image data..
I posted it just assuming the original poster might
need to perform both actions.


Unfortunately the problem was performing just the one action to start
with :(

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Chad | last post by:
I have a one dimensional byte array that stores the pixel information of my image. The image is 8-bit grayscale so each byte in the array holds a value from 0(black) to 255(white) for a single...
8
by: iyuen | last post by:
I'm having problems with converting a byte array to an image object~ My byte array is an picture in VB6 StdPicture format. I've used propertybag to convert the picture into base64Array format in...
1
by: KK | last post by:
Hi, I need to save certain content to SQL server and then use SQL Server indexing facility to search. SQL Server have recomended using Image data type with a filter type (for .htm, .doc etc..)...
7
by: lgbjr | last post by:
Hello All, I¡¯m using a context menu associated with some pictureboxes to provide copy/paste functionality. Copying the image to the clipboard was easy. But pasting an image from the clipboard...
3
by: grawsha2000 | last post by:
Hi, I'm trying to convert this simple string into image: Dim bytes() as byte()=System.text.Encoding.ascii.GetBytes("123") Dim memStream as System.IO.MemoryStream Dim img as image ...
9
by: Gregory.A.Book | last post by:
I am interested in converting sets of 4 bytes to floats in C++. I have a library that reads image data and returns the data as an array of unsigned chars. The image data is stored as 4-byte floats....
2
by: Laurent Navarro | last post by:
Hello, I am using a library which returns a byte containing RAW data, ie all pixels' color values coded in a byte array without header. I would like to save those data into a JPEG file so I...
2
by: Bjorn Sagbakken | last post by:
Hi. This story is about uploading jpg's, then resize them to fixed width or height and storing them to an SQL table. The only way I have found so far is to read the uploaded file to an...
10
by: =?Utf-8?B?UmludSBHb3BhbGFrcmlzaG5hIFBpbGxhaQ==?= | last post by:
Hi, Please help me to write a dll in C# , that will read each pages of a tiff image from a file and a memory stream object ( need two ways) and creatre a new tiff image object.The dll should...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.