Convert image and audio files to binary in Java
I want to convert an image and an audio file into a binary stream, process it and then reconstruct the image from the same binary stream in Java. How can I do that? Has anybody worked on this? Please help me out as soon as possible. Any hints or pseudocode will be highly appreciated. This is how I tried to do it but it just creates an empty file while reconstructing the image. For image to binary:-
File file = new File("E:\\image.jpg");
BufferedImage img = ImageIO.read(file);
开发者_StackOverflow社区 // write image to byte array in-memory (jpg format)
ByteArrayOutputStream b = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", b);
byte[] jpgByteArray = b.toByteArray();
// convert it to a String with 0s and 1s
StringBuilder sb = new StringBuilder();
for (byte by : jpgByteArray) {
sb.append(Integer.toBinaryString(by & 0xFF));
For binary to image:-
byte[] original = obj.orig_seq.getBytes();
InputStream in = new ByteArrayInputStream(original);
BufferedImage img = ImageIO.read(in);
ImageIO.write(img, "jpg",
new File("E:\\mypic_new.jpg"));
To use Binary String you can use this
StringBuilder sb = new StringBuilder();
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream("YourImage.jpg"))) {
for (int i; (i = is.read()) != -1;) {
String temp = "0000000" + Integer.toBinaryString(i).toUpperCase();
if (temp.length() == 1) {
sb.append('0');
}
temp = temp.substring(temp.length() - 8);
sb.append(temp).append(' ');
}
}
System.out.print(sb);
and here is your desired output
0000000 11111111 00000111 00011111 00101111 01111111
you can also use Hexadecimal and convert your file into a simple string like this (suggestion)
StringBuilder sb = new StringBuilder();
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream("YourFile.txt"))) {
for (int i; (i = is.read()) != -1;) {
String temp = Integer.toHexString(i).toUpperCase();
if (temp.length() == 1) {
sb.append('0');
}
sb.append(temp).append(' ');
}
}
System.out.print(sb);
and the output would be something like this
00 FF 07 1F 2F 7F
精彩评论