50,526
社区成员
发帖
与我相关
我的任务
分享
package test;
import java.io.*;
/**
*
* @author 陈星宇
* 纯手写, 请勿抄袭
*/
public class ImageUtil {
public static void main(String[] args) throws IOException {
//合成
imageComposite("f:/1", "f:/2"); // f:/1存放图片的文件夹, f:/2生成新文件的文件夹
//解析
createImage("f:/2", "f:/3"); // f:/2生成新文件的文件夹, f:/3还原文件存放的文件夹
}
/**
* 图片合成
* @param inDir 存放图片的路径
* @param outDir 存放合成文件的路径
* @throws IOException
*/
public static void imageComposite(String inDir, String outDir) throws IOException{
File file = new File(inDir);
File[] files = file.listFiles();
String fileName = createName(files);
for(File f : files){
writeFile(f, outDir+"/"+fileName);
}
}
//生成文件名
private static String createName(File[] files){
StringBuilder s = new StringBuilder();
for (File file : files) {
s.append(file.length()+file.getName().substring(file.getName().indexOf("."))+",");
}
return s.toString();
}
//将文件写入
private static void writeFile(File file, String fileName) throws IOException{
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(fileName, true);
byte[] b = new byte[1024];
int sum;
while((sum=fis.read(b))!=-1){
fos.write(b, 0, sum);
}
fis.close();
fos.close();
}
/**
* 图片合成
* @param inDir 存放合成文件的路径
* @param outDir 存放生成图片的路径
* @throws IOException
*/
public static void createImage(String inDir, String outDir) throws IOException{
File f = new File(inDir);
File[] files = f.listFiles();
for (File file : files) {
String[] imageNames = parseName(file);
writeFile(file, imageNames, outDir);
}
}
//解析出文件名
private static String[] parseName(File file) {
return file.getName().split(",");
}
//生成图片
private static void writeFile(File file, String[] imageNames, String outDir) throws IOException {
FileInputStream fis = new FileInputStream(file);
for(String str : imageNames){
FileOutputStream fos = new FileOutputStream(outDir+"/"+str, true);
int size = getSize(str);
byte[] b = new byte[size];
fis.read(b);
fos.write(b);
fos.close();
}
fis.close();
}
//从文件名中获取文件长度
private static int getSize(String s){
return Integer.parseInt(s.substring(0, s.indexOf(".")));
}
}