本以为是个非常简单的问题,实际试了却发现不是那么回事,真有点麻烦。
那些
URL
、
URI
、
File
等class,处理网络图片时总是报错,但本地图片就可以。
找到了一个看起来还算优雅的办法,直接上代码:
package image;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author zhaosen
* @date 2021年8月3日
* 由于java 读取网络图片很麻烦,在网上找到了这个办法,觉得还行
*/
public class ImageHelper {
/**
* 将图片写入到磁盘
*
* @param img 图片数据流
* @param zipImageUrl 文件保存时的名称
*/
public static void writeImageToDisk(byte[] img, String zipImageUrl) {
try {
File file = new File(zipImageUrl);
FileOutputStream fops = new FileOutputStream(file);
fops.write(img);
fops.flush();
fops.close();
System.out.println("图片已经写入" + zipImageUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] getImageFromNetByUrl(String strUrl) {
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
return btImg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从输入流中获取数据
*
* @param inStream 输入流
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[10240];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}
import image.ImageHelper;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.UUID;
public class Starter {
public static void main(String[] args) throws IOException, URISyntaxException {
//如果图片文件不是本地的,是网络图片,怎么办?
//ps: 没想到java读取网络图片还真有点麻烦
//读取网络图片
//java读取和处理网络图片还真麻烦 屮。 不得不转为本地文件处理
String imageUrl = "https://img-home.csdnimg.cn/images/20201120101655.png";
int index = imageUrl.lastIndexOf(".");
if (index == -1) {
return;
}
String extName = imageUrl.substring(index + 1);
byte[] imgByteArr = ImageHelper.getImageFromNetByUrl(imageUrl);
String uuid = UUID.randomUUID().toString();
String localFileName = String.format("%s.%s", uuid, extName);
ImageHelper.writeImageToDisk(imgByteArr, localFileName);
File localTempFile = new File(localFileName);
//删除临时文件
localTempFile.delete();
}
}