Converting image to byte array

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Luis Arvayo

    #1

    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.


  • Mark R. Dawson

    #2
    RE: Converting image to byte array

    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:
    [color=blue]
    > 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.
    >
    >
    >[/color]

    Comment

    • Robbe Morris [C# MVP]

      #3
      Re: Converting image to byte array



      --
      2004 and 2005 Microsoft MVP C#
      Robbe Morris


      Earn $$$ money answering .NET Framework
      messageboard posts at EggHeadCafe.com .




      "Luis Arvayo" <amorenopalma@p rodigy.net.mx> wrote in message
      news:eAU%23nG8j FHA.3900@TK2MSF TNGP10.phx.gbl. ..[color=blue]
      > 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.
      >
      >[/color]


      Comment

      • Jon Skeet [C# MVP]

        #4
        Re: Converting image to byte array

        Robbe Morris [C# MVP] <info@eggheadca fe.com> wrote:[color=blue]
        > http://www.eggheadcafe.com/PrintSear...asp?LINKID=799[/color]

        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 - <skeet@pobox.co m>
        Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

        If replying to the group, please do not mail me too

        Comment

        • Robbe Morris [C# MVP]

          #5
          Re: Converting image to byte array

          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


          Earn $$$ money answering .NET Framework
          messageboard posts at EggHeadCafe.com .




          "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message
          news:MPG.1d4d5f 68bc6349d398c50 1@msnews.micros oft.com...[color=blue]
          > Robbe Morris [C# MVP] <info@eggheadca fe.com> wrote:[color=green]
          >> http://www.eggheadcafe.com/PrintSear...asp?LINKID=799[/color]
          >
          > 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 - <skeet@pobox.co m>
          > http://www.pobox.com/~skeet
          > If replying to the group, please do not mail me too[/color]


          Comment

          • Jon Skeet [C# MVP]

            #6
            Re: Converting image to byte array

            Robbe Morris [C# MVP] <info@eggheadca fe.com> wrote:[color=blue]
            > 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.[/color]

            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..
            [color=blue]
            > I posted it just assuming the original poster might
            > need to perform both actions.[/color]

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

            --
            Jon Skeet - <skeet@pobox.co m>
            Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

            If replying to the group, please do not mail me too

            Comment

            • Robbe Morris [C# MVP]

              #7
              You are correct, I adjusted tip

              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



              Earn $$$ money answering .NET Framework
              messageboard posts at EggHeadCafe.com .




              "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message
              news:MPG.1d4db0 e341e39cc498c50 4@msnews.micros oft.com...[color=blue]
              > Robbe Morris [C# MVP] <info@eggheadca fe.com> wrote:[color=green]
              >> 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.[/color]
              >
              > 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..
              >[color=green]
              >> I posted it just assuming the original poster might
              >> need to perform both actions.[/color]
              >
              > Unfortunately the problem was performing just the one action to start
              > with :(
              >
              > --
              > Jon Skeet - <skeet@pobox.co m>
              > http://www.pobox.com/~skeet
              > If replying to the group, please do not mail me too[/color]


              Comment

              Working...