Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. Converting an Image to a Byte[] and visa versa

Converting an Image to a Byte[] and visa versa

Scheduled Pinned Locked Moved C#
graphicshelpwinformsdata-structuresxml
9 Posts 3 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    Gareth H
    wrote on last edited by
    #1

    What im trying to do is convert an image to a byte[], then write that byte array to an XML file as a string. I then want to be able to read back that file and convert the string to a btye array and then back to the image. //convert image to byte and then a string ASCIIEncoding encoding = new ASCIIEncoding(); byte[] imageArray = ImageToByteConvert(style.Image); string imageString = encoding.GetString(imageArray); //write string to file writer.WriteAttribute("Image", imageString); public byte[] ImageToByteConvert(Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms, ImageFormat.Gif); return ms.ToArray(); } ---- //read attribute "Image" attribute = domNode.Attributes["Image"]; if (attribute != null) { //convert to byte and set image byte[] imageByte = encoding.GetBytes(attribute.Value); retval.Image = ByteToImageConvert(imageByte); } public Image ByteToImageConvert(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; } The problem is im getting an error saying: 03/01/2007 14:31:31 XmlModelSerializer.SerializeContent; Exception: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(Stream stream, ImageFormat format) at XmlModelSerializer.ImageToByteConvert(Image imageIn) in line 61 at XmlModelSerializer.SerializeContent(IWriteContext context, SeverityNodeStyle style, IXmlWriter writer) in line 33 Line 61 is: imageIn.Save(ms, ImageFormat.Gif); Any ideas? Regards, Gareth.

    L M 2 Replies Last reply
    0
    • G Gareth H

      What im trying to do is convert an image to a byte[], then write that byte array to an XML file as a string. I then want to be able to read back that file and convert the string to a btye array and then back to the image. //convert image to byte and then a string ASCIIEncoding encoding = new ASCIIEncoding(); byte[] imageArray = ImageToByteConvert(style.Image); string imageString = encoding.GetString(imageArray); //write string to file writer.WriteAttribute("Image", imageString); public byte[] ImageToByteConvert(Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms, ImageFormat.Gif); return ms.ToArray(); } ---- //read attribute "Image" attribute = domNode.Attributes["Image"]; if (attribute != null) { //convert to byte and set image byte[] imageByte = encoding.GetBytes(attribute.Value); retval.Image = ByteToImageConvert(imageByte); } public Image ByteToImageConvert(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; } The problem is im getting an error saying: 03/01/2007 14:31:31 XmlModelSerializer.SerializeContent; Exception: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(Stream stream, ImageFormat format) at XmlModelSerializer.ImageToByteConvert(Image imageIn) in line 61 at XmlModelSerializer.SerializeContent(IWriteContext context, SeverityNodeStyle style, IXmlWriter writer) in line 33 Line 61 is: imageIn.Save(ms, ImageFormat.Gif); Any ideas? Regards, Gareth.

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #2

      You would get the very informative message "A generic error occurred in GDI+" for almost anything that can go wrong in Image.Save(). When saving to a file on disk it could be disk full, network disk disappeared, file is locked, file is read-only, whatever. I dont know which of these have an equivalent when saving to a memory stream. It might also be a basic limitation of the GIF format (e.g. too many colors). Are you sure you want GIF ? And it could be a GDI bug (unknown to me). Take your pick ! I would experiment with another format, say JPEG, at least to see if that works under identical conditions... :)

      Luc Pattyn

      G 1 Reply Last reply
      0
      • L Luc Pattyn

        You would get the very informative message "A generic error occurred in GDI+" for almost anything that can go wrong in Image.Save(). When saving to a file on disk it could be disk full, network disk disappeared, file is locked, file is read-only, whatever. I dont know which of these have an equivalent when saving to a memory stream. It might also be a basic limitation of the GIF format (e.g. too many colors). Are you sure you want GIF ? And it could be a GDI bug (unknown to me). Take your pick ! I would experiment with another format, say JPEG, at least to see if that works under identical conditions... :)

        Luc Pattyn

        G Offline
        G Offline
        Gareth H
        wrote on last edited by
        #3

        I tried changing the ImageFormat to .Jpeg, didnt change anything.

        L 1 Reply Last reply
        0
        • G Gareth H

          I tried changing the ImageFormat to .Jpeg, didnt change anything.

          L Offline
          L Offline
          Luc Pattyn
          wrote on last edited by
          #4

          Hi Gareth, I did some experiments with Image.Save() to memory stream, nothing went wrong. Do you have your problem with every image ? with the image(s) that goes wrong, does it fail on every attempt ? is anything special about such image ? (size, number of colors, way it was created, ...) ? what is its size ? do you have a file containing such image, if so could you mail one failing image to me ? furthermore, you could try to save GIF format to file instead of to memory stream, then have a look at the file to see how large it gets (i.e. how far the save operation succeeds), and (with hex viewer) possibly what is wrong. If saving to file also fails, I could have a look to that file too... Greetz

          Luc Pattyn

          G 1 Reply Last reply
          0
          • L Luc Pattyn

            Hi Gareth, I did some experiments with Image.Save() to memory stream, nothing went wrong. Do you have your problem with every image ? with the image(s) that goes wrong, does it fail on every attempt ? is anything special about such image ? (size, number of colors, way it was created, ...) ? what is its size ? do you have a file containing such image, if so could you mail one failing image to me ? furthermore, you could try to save GIF format to file instead of to memory stream, then have a look at the file to see how large it gets (i.e. how far the save operation succeeds), and (with hex viewer) possibly what is wrong. If saving to file also fails, I could have a look to that file too... Greetz

            Luc Pattyn

            G Offline
            G Offline
            Gareth H
            wrote on last edited by
            #5

            Hi Luc, It fails everytime on the same image and on different images. The image is only a 16x16 image, so is pritty small. How do i find out your email?, since i cant seem to view your profile. Regards, Gareth.

            G L 2 Replies Last reply
            0
            • G Gareth H

              Hi Luc, It fails everytime on the same image and on different images. The image is only a 16x16 image, so is pritty small. How do i find out your email?, since i cant seem to view your profile. Regards, Gareth.

              G Offline
              G Offline
              Gareth H
              wrote on last edited by
              #6

              Ive kind of fixed the problem. Its being caused because i dont have write permissions i think, because if i specifiy the actual file location, eg: C:\ci.gif, i dont get the error. But if i try to get the image from my get/set method, the error appears. The next problem i get through is when converting the image to bytes and visa versa. public string ImageToByteConvert(Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms, ImageFormat.Gif); string imageString = Convert.ToBase64String(ms.ToArray()); return imageString; } I then write that string to the XML file which works fine. But if i try to read it back byte[] imageByte = encoding.GetBytes(attribute.Value); retval.Image = ByteToImageConvert(imageByte); I get an error saying: 05/01/2007 11:57:37 XmlModelSave.ReadGraph; Exception: System.ArgumentException: Parameter is not valid. at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData) at System.Drawing.Image.FromStream(Stream stream) Which i believe to mean the bytes that i have just converted back from a string, arnt valid for the image im trying to create. But im unsure how to solve this. Regards, Gareth.

              1 Reply Last reply
              0
              • G Gareth H

                Hi Luc, It fails everytime on the same image and on different images. The image is only a 16x16 image, so is pritty small. How do i find out your email?, since i cant seem to view your profile. Regards, Gareth.

                L Offline
                L Offline
                Luc Pattyn
                wrote on last edited by
                #7

                Hi Gareth, I looked into your GIF file and did some experiments on it. I was able to read the image, modify and save it, but something weird happened to the background color. Upon closer inspection of your image, it seems to have a 6-bit color scheme, but a background color index of 255. This seems like an invalid combination. Hence: 1) I wonder how you created such an image in the first place 2) I am surprised GDI+ does not throw an exception (one of those nice "a generic error occured" messages) Regards,

                Luc Pattyn

                G 1 Reply Last reply
                0
                • L Luc Pattyn

                  Hi Gareth, I looked into your GIF file and did some experiments on it. I was able to read the image, modify and save it, but something weird happened to the background color. Upon closer inspection of your image, it seems to have a 6-bit color scheme, but a background color index of 255. This seems like an invalid combination. Hence: 1) I wonder how you created such an image in the first place 2) I am surprised GDI+ does not throw an exception (one of those nice "a generic error occured" messages) Regards,

                  Luc Pattyn

                  G Offline
                  G Offline
                  Gareth H
                  wrote on last edited by
                  #8

                  I didnt create the image, it was already created before i started working on this current project.

                  1 Reply Last reply
                  0
                  • G Gareth H

                    What im trying to do is convert an image to a byte[], then write that byte array to an XML file as a string. I then want to be able to read back that file and convert the string to a btye array and then back to the image. //convert image to byte and then a string ASCIIEncoding encoding = new ASCIIEncoding(); byte[] imageArray = ImageToByteConvert(style.Image); string imageString = encoding.GetString(imageArray); //write string to file writer.WriteAttribute("Image", imageString); public byte[] ImageToByteConvert(Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms, ImageFormat.Gif); return ms.ToArray(); } ---- //read attribute "Image" attribute = domNode.Attributes["Image"]; if (attribute != null) { //convert to byte and set image byte[] imageByte = encoding.GetBytes(attribute.Value); retval.Image = ByteToImageConvert(imageByte); } public Image ByteToImageConvert(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; } The problem is im getting an error saying: 03/01/2007 14:31:31 XmlModelSerializer.SerializeContent; Exception: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(Stream stream, ImageFormat format) at XmlModelSerializer.ImageToByteConvert(Image imageIn) in line 61 at XmlModelSerializer.SerializeContent(IWriteContext context, SeverityNodeStyle style, IXmlWriter writer) in line 33 Line 61 is: imageIn.Save(ms, ImageFormat.Gif); Any ideas? Regards, Gareth.

                    M Offline
                    M Offline
                    maysam gamini
                    wrote on last edited by
                    #9

                    Dear gareth111, as i see in this post you had a problem same as mine, please check this post soon, i really need your help, http://www.codeproject.com/Messages/3261881/Help-Database-Problem-Unknown-Information-in-an-Ac.aspx[^] thank you. With best Regards.

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups