在Java中将图像和音频文件转换为二进制文件

时间:2011-07-15 03:35:20

标签: image image-processing binary

我想将图像和音频文件转换为二进制流,处理它,然后在Java中从相同的二进制流重建图像。我怎样才能做到这一点?有人为此工作过吗?请尽快帮助我。任何提示或伪代码将受到高度赞赏。 这就是我尝试这样做的方法,但它只是在重建图像时创建一个空文件。 对于图像到二进制: -

        File file = new File("E:\\image.jpg");
        BufferedImage img = ImageIO.read(file);

        // 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));

二进制映像: -

        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"));

1 个答案:

答案 0 :(得分:2)

要使用二进制字符串,您可以使用此

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);

这是您想要的输出

0000000 11111111 00000111 00011111 00101111 01111111

您也可以使用十六进制并将文件转换为这样的简单字符串(建议)

 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);

并且输出将是这样的

00 FF 07 1F 2F 7F