如何调整目录中的图像大小? [英] How to resize images in a directory?
问题描述
这段代码试图在名为imgs的目录中调整图像大小。不幸的是,当我取消注释listFiles(..)循环 ImageIO.read(sourceImageFile)
将返回null。然而,在循环之外直接处理相同的文件( res(imgs / foto_3.jpg)
)的作品。显然,这个循环阻止了文件的读取。解决方案?
import java.awt.image。*;
import java.io. *;
import javax.imageio。*;
import static org.imgscalr.Scalr。*;
public class App {
public static void main(String [] args)抛出IOException {
// for(File sourceImageFile:new File(imgs ).listFiles()){
// res(imgs /+ sourceImageFile.getName());
//}
res(imgs / foto_3.jpg);
$ b public static void res(String arg)throws IOException {
文件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项目。
解决方案我已经改变了res方法:
pre preublic static void void(File arg)throws IOException {
if(arg.contains(。DS_Store)){
return;
$ b一个mac问题(或者应该按照建议过滤非图像文件)!
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()));
}
}
To reproduce the problem you can download the Maven project.
解决方案 I've changed res method:
public static void res(File arg) throws IOException {
if (arg.contains(".DS_Store")) {
return;
}
A mac-issue (or should filter non-image files, as was suggested)!
这篇关于如何调整目录中的图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!