'Getting error while converting string to image in java
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();
}
}
Solution 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jesper |
