This discussion is archived
6 Replies Latest reply: Aug 6, 2009 11:58 AM by 807588 RSS

BufferedImage to String and back

807588 Newbie
Currently Being Moderated
I want to convert an BufferedImage into a String and then get the BufferedImage again. I don't know why, the image seems to be altered after the conversion.

The image that has been used for the example can be downloaded here . Thanks in advanced.
package imagetoxml;

import java.awt.*;
import java.io.*;
import java.util.logging.*;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImageToXML {
    private JFrame frame;

    public ImageToXML()  {
        frame = new JFrame("Image to XML");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = frame.getContentPane();
        java.net.URL url = this.getClass().getResource("java.jpg");

        ImageIcon icon = new ImageIcon(url);
        BufferedImage bImage;
        Image image = icon.getImage();

        bImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bImage.createGraphics();
        g.drawImage(image, null, null);

        BufferedImage bImage2;
        Icon icon2;

        //image to string
        String imageString = imageToString(bImage, imagePath);

        //transport
        String imageString2 = imageString;

        //string to image
        bImage2 = stringToImage(imageString2);
        icon2 = new ImageIcon(bImage2);

        JLabel label2 = new JLabel(icon2);
        content.add(label2);
        
        frame.pack();
        frame.setVisible(true);
    }

    public String imageToString(BufferedImage bImage, String path)   {
        String imageString = null;

        String formatName = path.substring(path.lastIndexOf('.')+1, path.length());

        //image to bytes
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, formatName, baos);
            baos.flush();
            byte[] imageAsRawBytes = baos.toByteArray();
            baos.close();

            //bytes to string
            imageString = new String(imageAsRawBytes);
        } catch (IOException ex) {
            Logger.getLogger(ImageToXML.class.getName()).log(Level.SEVERE, null, ex);
        }

        return imageString;
    }

    public BufferedImage stringToImage(String imageString)    {
        //string to ByteArrayInputStream
        BufferedImage bImage = null;
        ByteArrayInputStream bais = new ByteArrayInputStream(imageString.getBytes());
        try {
            bImage = ImageIO.read(bais);
        } catch (IOException ex) {
            Logger.getLogger(ImageToXML.class.getName()).log(Level.SEVERE, null, ex);
        }

        return bImage;
    }

    public static void main(String[] args) {
        new ImageToXML();
    }
}
  • 1. Re: BufferedImage to String and back
    JosAH Newbie
    Currently Being Moderated
    Jurafsky wrote:
    I want to convert an BufferedImage into a String
    Believe me, you don't want that; convert a BufferedImage to a byte array or similar? Could be, but converting it to a String of chars; nah, you don't want to go there.

    kind regards,

    Jos
  • 2. Re: BufferedImage to String and back
    807588 Newbie
    Currently Being Moderated
    Thanks for the reply. :) My final purpose is to put a small image into an XML file. I know that is better to put the image into a file and include just the path, but my intention is to be able to share this file in other computer.

    How would you do it with bytes? Do you consider integeres as well?

    Anyway, I'd like to know why the current example is not working.
  • 3. Re: BufferedImage to String and back
    DrClap Expert
    Currently Being Moderated
    Yes, that's right, if you want to put something into an XML document then it has to be text. But the way to convert arbitrary binary data to text is NOT via the new String() constructor, because that assumes your bytes are supposed to represent text. Which they aren't.

    A common way to deal with this problem is to use Base64 encoding to convert the bytes to text.
  • 4. Re: BufferedImage to String and back
    807588 Newbie
    Currently Being Moderated
    Solved!! I added a few lines regarding BASE64 encryption and now the image is seen perfectly. The example below uses the libraries sun.misc.BASE64Decoder and sun.misc.BASE64Encoder, that are forbidden, but are shown here just to show the example. I'll find other BASE64 libraries or source code later.

    Thanks for the help, DrClap. ;)
    package imagetoxml;
    
    import java.awt.Container;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.imageio.ImageIO;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    public class ImageToXML {
        private JFrame frame;
    
        public ImageToXML()  {
            frame = new JFrame("Image to XML");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container content = frame.getContentPane();
    
            java.net.URL url = this.getClass().getResource("java.jpg");
    
            ImageIcon icon = new ImageIcon(url);
            //ImageIcon icon = new ImageIcon(imagePath);
            BufferedImage bImage;
            Image image = icon.getImage();
    
            bImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bImage.createGraphics();
            g.drawImage(image, null, null);
    
            BufferedImage bImage2;
            Icon icon2;
    
            //image to string
            String imageString = imageToString(bImage, imagePath);
    
            //transport
            String imageString2 = imageString;
    
            //string to image
            bImage2 = stringToImage(imageString2);
            icon2 = new ImageIcon(bImage2);
    
            JLabel label2 = new JLabel(icon2);
            content.add(label2);
            
            frame.pack();
            frame.setVisible(true);
        }
    
        public String imageToString(BufferedImage bImage, String path)   {
            String imageString = null;
    
            String formatName = path.substring(path.lastIndexOf('.')+1, path.length());
    
            //image to bytes
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ImageIO.write(bImage, formatName, baos);
                baos.flush();
                byte[] imageAsRawBytes = baos.toByteArray();
                baos.close();
    
                //bytes to string
                BASE64Encoder b64enc = new BASE64Encoder();
                imageString = b64enc.encode(imageAsRawBytes);
                //don't do this!!!
                //imageString = new String(imageAsRawBytes);
            } catch (IOException ex) {
                Logger.getLogger(ImageToXML.class.getName()).log(Level.SEVERE, null, ex);
            }
    
            return imageString;
        }
    
        public BufferedImage stringToImage(String imageString)    {
            //string to ByteArrayInputStream
            BufferedImage bImage = null;
            BASE64Decoder b64dec = new BASE64Decoder();
            try {
                byte[] output = b64dec.decodeBuffer(imageString);
                ByteArrayInputStream bais = new ByteArrayInputStream(output);
                bImage = ImageIO.read(bais);
            } catch (IOException e) {
                System.err.println("Error");
            }
    
            return bImage;
        }
    
        public static void main(String[] args) {
            new ImageToXML();
        }
    }
  • 5. Re: BufferedImage to String and back
    796440 Guru
    Currently Being Moderated
    Jurafsky wrote:
    Solved!! I added a few lines regarding BASE64 encryption
    Encoding, not encryption.

    </pb>
  • 6. Re: BufferedImage to String and back
    807588 Newbie
    Currently Being Moderated
    jverd wrote:

    Encoding, not encryption.
    Yep, you're right, they are very different things. Sorry...

    I ended using this BASE64 code that I got here (Base64Coder.java):
    http://www.source-code.biz/snippets/java/2.htm

    The final example code looks like this:
    package imagetoxml;
    
    import java.awt.Container;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.logging.*;
    import javax.imageio.*;
    import javax.swing.*;
    
    public class ImageToXML {
        private JFrame frame;
    
        public ImageToXML()  {
            frame = new JFrame("Image to XML");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container content = frame.getContentPane();
    
            java.net.URL url = this.getClass().getResource("java.jpg");
    
            ImageIcon icon = new ImageIcon(url);
            //ImageIcon icon = new ImageIcon(imagePath);
            BufferedImage bImage;
            Image image = icon.getImage();
    
            bImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bImage.createGraphics();
            g.drawImage(image, null, null);
    
            //image to string
            String imageString = imageToString(bImage, imagePath);
    
            //transport
            String imageString2 = imageString;
    
            //string to image
            BufferedImage bImage2 = stringToImage(imageString2);
            Icon icon2 = new ImageIcon(bImage2);
    
            JLabel label2 = new JLabel(icon2);
            content.add(label2);
            
            frame.pack();
            frame.setVisible(true);
        }
    
        public String imageToString(BufferedImage bImage, String path)   {
            String imageString = null;
    
            String formatName = path.substring(path.lastIndexOf('.')+1, path.length());
    
            //image to bytes
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ImageIO.write(bImage, formatName, baos);
                baos.flush();
                byte[] imageAsRawBytes = baos.toByteArray();
                baos.close();
    
                //bytes to string
                imageString = new String(Base64Coder.encode(imageAsRawBytes));
                //don't do this!!!
                //imageString = new String(imageAsRawBytes);*/
            } catch (IOException ex) {
                Logger.getLogger(ImageToXML.class.getName()).log(Level.SEVERE, null, ex);
            }
    
            return imageString;
        }
    
        public BufferedImage stringToImage(String imageString)    {
            //string to ByteArrayInputStream
            BufferedImage bImage = null;
            try {
                byte[] output = Base64Coder.decode(imageString);
                ByteArrayInputStream bais = new ByteArrayInputStream(output);
                bImage = ImageIO.read(bais);
            } catch (IOException ex) {
                Logger.getLogger(ImageToXML.class.getName()).log(Level.SEVERE, null, ex);
            }
    
            return bImage;
        }
    
        public static void main(String[] args) {
            new ImageToXML();
        }
    }