473,669 Members | 2,335 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Ima ge.Save(ms, System.Drawing. Imaging.ImageFo rmat.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.Ima ge = 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 41613
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.Ima ge.Save(ms, System.Drawing. Imaging.ImageFo rmat.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.Ima ge = 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**********@p rodigy.net.mx> wrote in message
news:eA******** ********@TK2MSF TNGP10.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.Ima ge.Save(ms, System.Drawing. Imaging.ImageFo rmat.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.Ima ge = 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**@eggheadca fe.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.FromStrea m - 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.Positio n = 0;

after the call to Write and before the call to Image.FromStrea m.

(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.co m>
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.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Robbe Morris [C# MVP] <in**@eggheadca fe.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.FromStrea m - 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.Positio n = 0;

after the call to Write and before the call to Image.FromStrea m.

(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.co m>
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**@eggheadca fe.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 = ConvertImageToB yteArray(origin al);
Image converted = ConvertByteArra yToImage(bytes) ;
Image thumb = converted.GetTh umbnailImage
(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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6
I only use ConvertByteArra yToImage 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.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Robbe Morris [C# MVP] <in**@eggheadca fe.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 = ConvertImageToB yteArray(origin al);
Image converted = ConvertByteArra yToImage(bytes) ;
Image thumb = converted.GetTh umbnailImage
(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.co m>
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
3850
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 pixel. I need a way to save this this byte array as a gif. Does anyone have any suggestions???
8
4558
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 XML, and embedded the array as some child element in an xml file, i.e.: <Mask>bHQAAH4AAABCTX4AAAAAAAAAPgAAACgAAAAQAAAAEAAAAAEAAQAAAAAAQAAAAAAAAAAAAA AA AAAAAAAAAAAAAAAA////AP//AAD//wAA//8AAP//AAD/7wAA//cAALtzAABVeQAAVUAAAFVA...
1
1973
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..) Now, because of this I save normal html content also in binary format in the Image field.
7
11615
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 is proving to be more difficult. These pictureboxes are bound to an AccessDB. If the user wants to add an image, they select an image using an OpenFileDialog: Dim result As DialogResult = Pic_Sel.ShowDialog() If (result = DialogResult.OK) Then
3
6641
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 memStream.Write(bytes,0.bytes.length)
9
30508
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. How can I convert the sets of 4 bytes to floats? Thanks, Greg Book
2
10342
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 tried to use the MetaFile class. byte data; (...) // Creating the RAW image through the DLL call. MemoryStream memoryStream = new MemoryStream(data);
2
2681
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 image-variable, then using the method of creating thumbnails for the resizing. Next, I write this to a temp file on the disk, and read the file back to a byte array in order to insert/update the SQL table. Now, this works well, and even fast enough, no...
10
10709
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 return the combined tif image object. Thnks in advance Rinu G P
0
8462
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8382
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8893
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8802
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8586
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6209
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
2792
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2028
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1787
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.