将临时 .jpg 文件保存到计算机
Save temporary .jpg file to computer
java中有一个方法叫做.createTempFile
,我用它来生成图片和returns文件的方法。这是部分代码:
File jpgFile = File.createTempFile("tmp, ".jpg");
//fill the file with information ...
return jpgFile;
当我访问主方法中的方法时,我得到一个文件。现在我的问题是:我怎样才能保存这个文件?我尝试这样做:
File f = generateJPG(); // (the method that is explained above)
File out = new File("C:/fileJPG.jpg");
FileInputStream fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileWriter fstream = new FileWriter(out, true);
BufferedWriter outw = new BufferedWriter(fstream);
String aLine = null;
while ((aLine = in.readLine()) != null) {
outw.write(aLine);
outw.newLine();
}
in.close();
outw.close();
但这行不通,只会给我一张充满随机像素的非常混乱的图片。那么如何将这个临时文件保存到我的电脑上呢?
我刚刚找到了解决方案。我用了 ImageIO
和 BufferedImage
,就像 @JordiCastilla 说的那样,效果很好。这是代码:
File f = generateJPG();
BufferedImage image = ImageIO.read(f);
File out = new File("C:/fileJPG.jpg");
ImageIO.write(image, "jpg", out);
java中有一个方法叫做.createTempFile
,我用它来生成图片和returns文件的方法。这是部分代码:
File jpgFile = File.createTempFile("tmp, ".jpg");
//fill the file with information ...
return jpgFile;
当我访问主方法中的方法时,我得到一个文件。现在我的问题是:我怎样才能保存这个文件?我尝试这样做:
File f = generateJPG(); // (the method that is explained above)
File out = new File("C:/fileJPG.jpg");
FileInputStream fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileWriter fstream = new FileWriter(out, true);
BufferedWriter outw = new BufferedWriter(fstream);
String aLine = null;
while ((aLine = in.readLine()) != null) {
outw.write(aLine);
outw.newLine();
}
in.close();
outw.close();
但这行不通,只会给我一张充满随机像素的非常混乱的图片。那么如何将这个临时文件保存到我的电脑上呢?
我刚刚找到了解决方案。我用了 ImageIO
和 BufferedImage
,就像 @JordiCastilla 说的那样,效果很好。这是代码:
File f = generateJPG();
BufferedImage image = ImageIO.read(f);
File out = new File("C:/fileJPG.jpg");
ImageIO.write(image, "jpg", out);