问题描述
此代码尝试在名为imgs"的目录中调整图像大小.不幸的是,由于某种原因,当我取消对 listFiles(..) 循环的注释时 ImageIO.read(sourceImageFile)
将返回 null.然而,在循环外直接处理相同的文件 (res("imgs/foto_3.jpg")
) 有效.很明显,这个循环阻止了文件被读取.解决方案?
This code attempts to resize images in a directory called "imgs". Unfortunately for some reason when I uncomment the listFiles(..) loop ImageIO.read(sourceImageFile)
will return null. Yet processing the same file straightaway outside the loop (res("imgs/foto_3.jpg")
) works. So apparently, this loop is preventing the files from being read. Solutions?
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import static org.imgscalr.Scalr.*;
public class App {
public static void main(String[] args) throws IOException {
// for (File sourceImageFile : new File("imgs").listFiles()) {
// res("imgs/"+sourceImageFile.getName());
// }
res("imgs/foto_3.jpg");
}
public static void res(String arg) throws IOException {
File sourceImageFile = new File(arg);
BufferedImage img = ImageIO.read(sourceImageFile);
BufferedImage thumbnail = resize(img, 500);
thumbnail.createGraphics().drawImage(thumbnail, 0, 0, null);
ImageIO.write(thumbnail, "jpg", new File("resized/" + sourceImageFile.getName()));
}
}
要重现该问题,您可以下载 Maven 项目.>
To reproduce the problem you can download the Maven project.
推荐答案
我改变了 res 方法:
I've changed res method:
public static void res(File arg) throws IOException {
if (arg.contains(".DS_Store")) {
return;
}
一个 mac 问题(或者应该过滤非图像文件,如建议的那样)!
A mac-issue (or should filter non-image files, as was suggested)!
这篇关于如何调整目录中的图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!