1、从网络获取图片资源下载到本地
public static void main(String[] args) throws IOException { String path = "https://wwwqWuPi5lTRK5TyI9zyVGg3fc="; long newPath = System.currentTimeMillis(); String path1 = "C:\\Users\\a\\Desktop\\qrcode\\"+newPath+".jpg"; locaImage(path,path1); } /** * 根据地址获得数据的字节流 * @param strUrl * @return */ 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 * @return * @throws Exception */ 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(); } /** * 将图片写入到磁盘 * @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(); } } /** * 通过资源地址从网络获取图片资源并下载 * @param fileUrl * @param fileZipUrl */ public static void locaImage(String fileUrl,String fileZipUrl){ byte[] btImg = getImageFromNetByUrl(fileUrl); if (null != btImg && btImg.length > 0) { writeImageToDisk(btImg, fileZipUrl); } }
2、从网络获取图片资源先压缩后保存到本地
public static void main(String[] args) throws IOException { String path = "https://wwwt/Kl&Expires=1593670794&Signature=xcUHqWuPi5lTRK5TyI9zyVGg3fc="; long newPath = System.currentTimeMillis(); String path2 = "C:\\Users\\a\\Desktop\\qrcode\\789.jpg"; URL url = new URL(path); Thumbnails.of(url).outputQuality(0.5f).scale(0.5f).toFile(path2); }
3、从网络获取图片资源先保存到本地再压缩再保存
public static void main(String[] args) throws IOException { String path = "https://wwweyId=l0klDK1vEUxht/Kl&Expires=1593670794&Signature=xcUHqWuPi5lTRK5TyI9zyVGg3fc="; long newPath = System.currentTimeMillis(); String path1 = "C:\\Users\\a\\Desktop\\qrcode\\"+newPath+".jpg"; String path2 = "C:\\Users\\a\\Desktop\\qrcode\\789.jpg"; locaImage(path,path1); Thumbnails.of(path1).outputQuality(0.5f).scale(0.5f).toFile(path2); }
原文:https://www.cnblogs.com/Lk-skyhorse/p/13220667.html