Java : Writing a String to a JPG File

标签 java string stream java-io

好吧,我正在编写一个小程序,本应该需要 10 分钟才能完成,但我遇到了不可预见的问题。

该程序应该接收我在旧手机上的保管库程序中的一些旧文件,它们基本上是 Jpg 文件,但在文件前面添加了“模糊”文本。

下面是我的代码逻辑

  1. 获取文件的文件夹输入,
  2. 创建一个包含每个实际文件的数组列表。
  3. 调用 ConvertFiles 将文件转换为字符串,
  4. 使用子字符串删除前 8 个字符,并将该临时文件保存到另一个包含字符串的数组列表中。
  5. 将该字符串解码为 base64 并将其输入到 bytearrayinputstream 中,并将其保存到缓冲图像中。

这就是问题发生的地方。我的内容一直到 ImageIO.read(bis),因此当它尝试写入新文件时,它会抛出 image == null 来自图像类型说明符。我已经尝试了多种解码和编码字符串的方法,但需要任何帮助,如果需要更多信息,我将提供!

public class ImageConvert {

    private File folder;
    private ArrayList<File> files;
    private ArrayList<String> stringFiles = new ArrayList<>();
    private ArrayList<BufferedImage> bfImages = new ArrayList<>();
    boolean isRunning = true;
    Scanner scanner = new Scanner(System.in);
    String folderPath;

    public static void main(String[] args) {
        ImageConvert mc = new ImageConvert();
        mc.mainCode();
    }

    public void mainCode(){
        System.out.println("Please enter the folder path: ");
        folderPath = scanner.nextLine();
        folder = new File(folderPath);
        //System.out.println("folderpath: " + folder);
        files = new ArrayList<File>(Arrays.asList(folder.listFiles()));
        convertFiles();
    }

    public void convertFiles(){
        for(int i = 0; i < files.size(); i++){
            try {
                String temp = FileUtils.readFileToString(files.get(i));
                //System.out.println("String " + i + " : " + temp);
                stringFiles.add(temp.substring(8));
            } catch (IOException ex) {
                Logger.getLogger(ImageConvert.class.getName()).log(Level.SEVERE,
                                                                    null, ex);
            }
        }

        //System.out.println("Converted string 1: " + stringFiles.get(0));
        for(int j = 0; j < stringFiles.size(); j++){

            BufferedImage image = null;
            byte[] imageByte;

            try {
               BASE64Decoder decoder = new BASE64Decoder();
               imageByte = decoder.decodeBuffer(stringFiles.get(j));
               System.out.println(imageByte.toString());
               ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
               image = ImageIO.read(bis);
               bis.close();
               bfImages.add(image);
          } catch (IOException ex) {
               Logger.getLogger(ImageConvert.class.getName()).log(Level.SEVERE,
                                                                   null, ex);
          }

        }


        System.out.println("Image 1: " + bfImages.get(0));

        for(int k = 0; k < bfImages.size(); k++){
            try {
                ImageIO.write(bfImages.get(k), "jpg",
                              new File(folderPath + "/" + k + ".jpg"));
            } catch (IOException ex) {
                Logger.getLogger(ImageConvert.class.getName()).log(Level.SEVERE,
                                                                    null, ex);
            }
        }

    }

}

This is an example of my files:

最佳答案

以下示例使用您的问题中包含的文件。您不需要进行任何解码,只需将文件读入内存,存储 8 字节 String,然后将剩余字节从 8 字节偏移量写入 jpg .

只需调整以下方法即可适用于您的:“文件的文件夹输入”。您不需要包含每个实际 jpg 文件的 ArrayList

public void convertFiles() {
    File imgFile;
    byte[] bytes;
    FileOutputStream fos;
    String temp;

    for (int i = 0; i < files.size(); i++) {
        temp = "";

        try {
            // 'read' method can be found below
            bytes = read(files.get(i));

            // read the 8 byte string from the beginning of the file
            for(int j = 0; j < 8; j++) {
                temp += (char) bytes[j];
            }

            imgFile = new File("img.jpg");

            // points to './img.jpg'
            fos = new FileOutputStream(imgFile);

            // write from offset 8 to end of 'bytes'
            fos.write(bytes, 8, bytes.length - 8);

            fos.close();
        } catch (FileNotFoundException e) {
            // Logger stuff
        } catch (IOException ex) {
            // Logger stuff
        }

        System.out.println("[temp]:> " + temp);
    }

}

read(File file) 方法改编自社区 wiki 对 File to byte[] in Java 的回答

public byte[] read(File file) throws IOException {
    ByteArrayOutputStream ous = null;
    InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1) {
            ous.write(buffer, 0, read);
        }
    } finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
        }

        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }

    return ous.toByteArray();
}

输出:

[temp]:> obscured

图像文件:

Decoded image file.

关于Java : Writing a String to a JPG File,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35423531/

相关文章:

java - 谷歌分析 403 : Forbidden with p12 key in Java

java - 启动 Eclipse 平台时出现 MESSAGE 异常

python - 如何将 Python 字典序列化为字符串,然后再返回字典?

c++ - 什么是 `CString` ?

python - 将单个字节写入 python 3.x 中的文件

Java : Bound mismatch error

java - 如何用星号替换文本中的特定单词“*"equal to the word' s 长度?

c# - 将 ReadAsStreamAsync 与 StreamReader 一起使用时出现 "stream was not readable"ArgumentException

php - 我可以使用不是磁盘上文件的证书来使用 SSL 套接字吗? (即在数据库中)

java - 使用 Spring Boot 或 Hibernate Validator 验证日期