直接祭出代码
public static void main(String[] args) {
String url = "http://img3.myhsw.cn/2017-06-23/xf3peqec.jpg";
String path = "/test/img/1.jpg";
getPicture1(url,path);
// getPicture2(url,path);
}
// 方法一
private static void getPicture1(String urlpath, String path) {
URL url = null;
try {
url = new URL(urlpath);
DataInputStream dataInput = new DataInputStream(url.openStream());
FileOutputStream fileOutput = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInput.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutput.write(output.toByteArray());
dataInput.close();
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//方法二
public static void getPicture2(String url, String path) {
BufferedImage image = null;
try {
image = ImageIO.read(new URL(url));
} catch (Exception e) {
e.printStackTrace();
}
File file = new File(path).getAbsoluteFile();
File dir = file.getParentFile();
if (!dir.isDirectory())
dir.mkdirs();
System.out.println(path);
try {
ImageIO.write(image, "jpg", new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
两种方法都可以
直接复制的注意修改path
!!!如果图片打不开 图片格式不对
可以读取图片的格式为:[BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
文件后缀名有时候不是实际的文件格式,可以下载下来看看前缀 例如 :RIFF WEBPVP8就是webp格式
1389

被折叠的 条评论
为什么被折叠?



