用Java写一段代码,将多张图片压缩,每十张放到一个文件夹
时间: 2024-03-02 17:49:13 浏览: 18
以下是一个简单的Java代码示例,可以将指定目录下的多张图片压缩成每10张图片一个文件夹:
```java
import java.io.*;
import java.util.List;
import java.util.ArrayList;
import java.util.zip.*;
public class ImageCompressor {
public static void main(String[] args) throws Exception {
String sourceFolder = "source";
String outputFolder = "output";
int imagesPerFolder = 10;
File folder = new File(sourceFolder);
File[] files = folder.listFiles();
List<File> images = new ArrayList<File>();
for (File file : files) {
String name = file.getName().toLowerCase();
if (name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png")) {
images.add(file);
}
}
int folderIndex = 0;
int count = 0;
byte[] buffer = new byte[1024];
ZipOutputStream out = null;
for (File image : images) {
if (count == 0) {
File output = new File(outputFolder, String.format("%03d", ++folderIndex));
output.mkdirs();
out = new ZipOutputStream(new FileOutputStream(new File(output, "images.zip")));
out.setMethod(ZipOutputStream.DEFLATED);
}
FileInputStream in = new FileInputStream(image);
ZipEntry entry = new ZipEntry(image.getName());
out.putNextEntry(entry);
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.closeEntry();
if (++count == imagesPerFolder) {
out.close();
count = 0;
}
}
if (out != null) {
out.close();
}
}
}
```
以上示例中,将源文件夹"source"中的所有图片文件压缩成每10张图片一个文件夹的方式存储到"output"目录下。每个文件夹中包含一个名为"images.zip"的压缩文件,其中包含了10张图片,文件夹名称为"001"、"002"、"003"等。