文件系列二 :下载网络文件、添加水印

说明

  • 下载网络文件
  • 下载网络文件并添加水印

示例代码

package com.utils;import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.UriUtils;import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;/*** @Description:* @Author: hmm* @Date: 2021/4/26*/
public class Test {/*** 根据url下载网络文件至本地** @param url      文件地址* @param dir      存储目录* @param filename 存储文件名 含后缀* @return 下载后的文件存储路径*/public static void downloadHttpUrl(String url, String dir, String filename) throws IOException {//        URL urlPath = new URL(url);
//        下载文件中文名处理URL urlPath = new URL(UriUtils.encodePath(url, "UTF-8"));File file = new File(dir);if (!file.exists()) {file.mkdirs();}FileUtils.copyURLToFile(urlPath, new File(dir + filename));}/*** 从网络Url中下载文件** @param url      文件地址* @param dir      存储目录* @param filename 存储文件名 含后缀* @throws IOException*/public static void downLoadFromUrl(String url, String dir, String filename) throws IOException {URL urlPath = new URL(url);HttpURLConnection conn = (HttpURLConnection) urlPath.openConnection();//设置超时间为3秒conn.setConnectTimeout(3 * 1000);//防止屏蔽程序抓取而返回403错误conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");//得到输入流InputStream inputStream = conn.getInputStream();//获取自己数组byte[] getData = readInputStream(inputStream);//文件保存位置File saveDir = new File(dir);if (!saveDir.exists()) {saveDir.mkdir();}File file = new File(saveDir + File.separator + filename);FileOutputStream fos = new FileOutputStream(file);fos.write(getData);if (fos != null) {fos.close();}if (inputStream != null) {inputStream.close();}}/*** 从输入流中获取字节数组** @param inputStream* @return* @throws IOException*/public static byte[] readInputStream(InputStream inputStream) throws IOException {byte[] buffer = new byte[1024];int len = 0;ByteArrayOutputStream bos = new ByteArrayOutputStream();while ((len = inputStream.read(buffer)) != -1) {bos.write(buffer, 0, len);}bos.close();return bos.toByteArray();}//TODO:************************ 下载并添加水印 ************************/*** 从网络Url中下载文并添加水印** @param url      文件地址* @param dir      存储目录* @param filename 存储文件名 含后缀* @param iconPath 水印图片路径* @throws IOException*/public static void downLoadAndMarkWater(String url, String dir, String filename, String iconPath) {try{HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();conn.setReadTimeout(5000);conn.setConnectTimeout(5000);conn.setRequestMethod("GET");String targetPath = dir + filename + ".jpg";if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {InputStream inputStream = conn.getInputStream();// 添加图片水印boolean mark = MarkImage.markImageByIcon(iconPath, inputStream, targetPath, null, "jpg");}}catch (Exception e){System.err.println("获取网络图片出现异常,图片路径为:" + url);e.printStackTrace();}}/*** 给图片添加图片水印、可设置水印图片旋转角度** @param iconPath   水印图片路径* @param srcImage   源图片文件流* @param targetPath 目标图片路径* @param degree     水印图片旋转角度* @param formatName 目标图片格式*/public static boolean markImageByIcon(String iconPath, InputStream srcImage, String targetPath, Integer degree, String formatName) {if (StringUtils.isBlank(iconPath) || StringUtils.isBlank(targetPath) || StringUtils.isBlank(formatName)) {return false;}OutputStream os = null;try {Image srcImg = ImageIO.read(srcImage);BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);int srcWidth = srcImg.getWidth(null);int srcHeight = srcImg.getHeight(null);// 1、得到画笔对象Graphics2D g = buffImg.createGraphics();// 2、设置对线段的锯齿状边缘处理g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);// 3、设置水印旋转if (null != degree) {g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);}// 4、水印图片的路径 水印图片一般为gif或者png的,这样可设置透明度ImageIcon imgIcon = new ImageIcon(iconPath);// 5、得到Image对象。Image img = imgIcon.getImage();int iconWidth = img.getWidth(null);int iconHeight = img.getHeight(null);double dmarkWidth = srcWidth * 0.9;// 设置水印的宽度为图片宽度的0.9倍double dmarkHeight = dmarkWidth * ((double) iconWidth / (double) iconHeight);//强转为double计算宽高比例int imarkWidth = (int) dmarkWidth;int imarkHeight = (int) dmarkHeight;// 6、水印图片的位置int x = (srcWidth - imarkWidth) / 2;int y = (srcHeight - imarkHeight) / 2;g.drawImage(img, x, y, imarkWidth, imarkHeight, null);g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));// 7、释放资源g.dispose();// 8、生成图片os = new FileOutputStream(targetPath);ImageIO.write(buffImg, formatName, os);return true;} catch (Exception e) {e.printStackTrace();} finally {try {if (null != os) {os.close();}} catch (Exception e) {e.printStackTrace();}}return false;}public static void main(String[] args) {
//        String url = "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";String url ="http://10.0.0.0:8080/image/202106011442318460.jpg";String filename = "1_" + UUID.randomUUID() + ".jpg";String iconPath = "D://test/icon.png";try {// copyURLToFileTest.downloadHttpUrl(url, "D:/test/", filename);// 文件流filename = "2_" + UUID.randomUUID() + ".jpg";Test.downLoadFromUrl(url, "D:/test/", filename);filename = "w_" + UUID.randomUUID() + ".jpg";Test.downLoadAndMarkWater(url, "D:/test/", filename, iconPath);} catch (IOException ex) {ex.printStackTrace();}}
}

在这里插入图片描述