1

I am facing an issue while converting String to image. After converting string image it is saying invalid file format.

public class FileExample {

    public static void main(String[] args) throws IOException {
        File file = new File("G:\\designpatterns\\image002.jpg");
        FileInputStream fis = new FileInputStream("G:\\designpatterns\\image002.jpg");
        byte bytes[]= new byte[(int)file.length()];
        fis.read(bytes);
        String rawString = new String(bytes);
        
          FileOutputStream fos = new
          FileOutputStream("G:\\designpatterns\\image001.jpg");
          fos.write(rawString.getBytes()); 
          fis.close();
          fos.close();

    }

}
1
  • Even if that did work - see answer as to why it won't - why are you doing that anyway? All you're doing is copying a file. Use the apt method Commented Apr 25, 2022 at 10:08

1 Answer 1

1

A String is not a suitable container for arbitrary bytes.

When you try to create a String from bytes, like you are doing here:

String rawString = new String(bytes);

then the constructor of class String is going to interpret those bytes using a character encoding and try to convert them to characters.

Because the bytes of an image file do not represent text that is encoded with some character encoding, this will fail.

Do not use a String as a container for arbitrary binary data.

If you need to store binary data, such as the content of an image file, in the form of characters, use something like Base64 encoding.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.