一开始用的文件排序方法是最简单的String的compareTo方法,但是这个方法有个致命错误。
他单纯一位一位按照字符的ASCII码比较,这样会导致26>259的情况发生。
改进:
Collections.sort(fl, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
String Name1 = o1.getName();
String Name2 = o2.getName();
if (Name1.length() < Name2.length()) {
return -1;
}
if (Name1.length() == Name2.length()) {
return Name1.compareTo(Name2);
}
return 1;
}
});
此外由之前生成的gif,默认背景是黑色的,对于黑色图片会导致看不见图像
用e.setBackground(Color.white);
就能改变图片的背景色。
新代码:
package gif;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import javax.imageio.ImageIO;
public class Gif {
public static void main(String[] args) throws IOException {
String pic;
String gif;
String bool;
int time = 0;
Scanner sc = new Scanner(System.in);
System.out.println("png路径:");
pic = sc.next();
System.out.println("是否改变生成gif的路径(默认当前文件夹)(Y/N):");
bool = sc.next();
if ("Y".equals(bool)) {
System.out.println("新路径:");
gif = sc.next();
} else {
gif = pic;
}
System.out.println("请输入背景颜色(r, g, b):");
int r = sc.nextInt();
int g = sc.nextInt();
int b = sc.nextInt();
Color color = new Color(r, g, b);
System.out.println("请输入delayTime:");
int playtime = sc.nextInt();
sc.close();
StringBuilder newgifBuilder = new StringBuilder(gif).append("\\").append(new File(pic).getName());
gif = newgifBuilder.toString();
jpgToGif(pic, gif, playtime, time, bool, color);
System.out.println("done");
}
private static void jpgToGif(String pic, String gif, int playtime, int time, String bool, Color color) throws IOException {
AnimatedGifEncoder e = new AnimatedGifEncoder();
List<File> fl = Arrays.asList(new File(pic).listFiles());
if (0 != time) {
gif = gif.replace(new File(gif).getName(), new File(pic).getName());
if (!"Y".equals(bool)) {
gif = gif.replace(new File(pic).getName(), new File(pic).getName() + "\\" + new File(pic).getName());
}
}
StringBuilder newgifBuilder = new StringBuilder(gif).append(".gif");
String gp = newgifBuilder.toString();
Collections.sort(fl, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
String Name1 = o1.getName();
String Name2 = o2.getName();
if (Name1.length() < Name2.length()) {
return -1;
}
if (Name1.length() == Name2.length()) {
return Name1.compareTo(Name2);
}
return 1;
}
});
e.setRepeat(0);
e.start(gp);
for(File sf : fl) {
if (sf.isDirectory()) {
StringBuilder newpicpath = new StringBuilder(pic).append("\\").append(sf.getName());
String newpic = newpicpath.toString();
time++;
jpgToGif(newpic, gp, playtime, time, bool, color);
}
if (sf.getName().endsWith(".png")) {
BufferedImage src = (BufferedImage)ImageIO.read(sf);
e.setDelay(playtime);
e.addFrame(src);
e.setBackground(color);
}
}
}
}