我正在尝试从请求的网站中提取图像,然后将其保存到文件夹中。唯一的问题是我从中提取图像的网站有多种图像格式。所以图像的扩展名可能是png,jpg或gif。我需要保存所有这些,但我不知道如何告诉我的程序提取多种格式而不只是一种...
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main( String[] args )
{
int avatarnum = 1;
String extension = null;
BufferedImage image = null;
extension = "jpg";
while(avatarnum <= 1000){
try {
URL url = new URL("http://forum.blockland.us/avatarUpload/avatar_"+avatarnum+"."+extension);
image = ImageIO.read(url);
try{
ImageIO.write(image, extension,new File("C:\\test\\"+avatarnum+"."+extension));
System.out.println("Write successful");
avatarnum ++;
} catch(Exception e){
System.out.println("Printing stacktrace");
e.printStackTrace();
}
avatarnum ++;
} catch (IOException e) {
System.out.println("File not found! " + avatarnum);
System.out.println("Adding one to variable and retrying..");
avatarnum ++;
}
}
System.out.println("Done");
}
}
截至目前,只有jpg图像从网站中提取并保存到文件夹中 出于测试目的,它只会从网站上提取1,000张图片。
如果有人想知道的话,我会用它制作一个“头像数据库”。
非常感谢你!
答案 0 :(得分:1)
您需要迭代多种图像格式(扩展名):
public static void main(String[] args) {
int avatarnum = 1;
BufferedImage image = null;
String[] extensions = { "jpg", "png", "gif", "bmp" };
while (avatarnum <= 1000) {
for (String extension : extensions) {
try {
URL url = new URL("http://forum.blockland.us/avatarUpload/avatar_" + avatarnum + "." + extension);
image = ImageIO.read(url);
try {
ImageIO.write(image, extension, new File("C:\\test\\" + avatarnum + "." + extension));
System.out.println("Write successful");
} catch (Exception e) {
System.out.println("Error on save the image");
}
} catch (IOException e) {
System.out.println("File not found! " + avatarnum + "." + extension);
}
}
avatarnum++;
}
System.out.println("Done");
}
答案 1 :(得分:-1)
使用包含所有有效扩展名的数组
String[] extensions = {"jpg", "png", "gif" };
在检索网址
时循环遍历所有这些内容try {
for (String extension: extensions){
try {
URL url = new URL("http://forum.blockland.us/avatarUpload/avatar_"+avatarnum+"."+extension);
image = ImageIO.read(url);
} catch (Exception e){
//Wrong extension (or other kind of error)
}
}
...
对于每个图像,它将以错误的扩展名失败,但会使用正确的
来检索