工具类收集

图片处理工具类:

package org.springblade.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.config.CustomFileConfig;
import sun.misc.BASE64Decoder;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片处理工具类
 *
 * @author wq
 * @date 2021/4/27 23:19
 */
@Slf4j
public class ImageUtil {

	@Resource
	private CustomFileConfig customFileConfig;

	/**
	 * 图片转base64
	 *
	 * @param base64 data:image/jpeg;base64,/9j/4AA...
	 * @return 上传到OSS服务器后返回的结果
	 */
	public JSONObject base64ToPicUrl(String base64) {
		String targetPath = "";
		if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
			log.info("Windows系统...");
			targetPath = customFileConfig.getWindows();
		} else {
			log.info("Linux系统...");
			targetPath = customFileConfig.getLinux();
		}
		String currPath = decodeBase64(base64, targetPath, "jpg", false);
		// 将生成的PDF上传到OSS服务器,保存返回的访问链接到用电信息表
		Map<String, Object> params = new HashMap<>();
		params.put("file", FileUtil.file(currPath));
		String resultData = HttpUtil.post(CustomConst.OSS_URL, params);
		return (JSONObject) JSON.parse(resultData);
	}

	public static String decodeBase64(String base64,String filePath,String suffix,boolean isSafe){
		if(StringUtils.isBlank(base64)||StringUtils.isBlank(filePath)||StringUtils.isBlank(suffix)){
			throw new NullPointerException();
		}
		OutputStream out=null;
		String fileName=null;
		try {
			byte[] b=new byte[2048];
			if(isSafe){
				java.util.Base64.Decoder decoder = java.util.Base64.getUrlDecoder();
				b = decoder.decode(base64);
			}else{
				BASE64Decoder decoder = new BASE64Decoder();
				b = decoder.decodeBuffer(base64.substring(base64.indexOf(",") + 1));
			}
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			File file=new File(filePath);
			if(!file.exists()){
				file.mkdirs();
			}
			fileName=filePath+System.currentTimeMillis()+"."+suffix;
			out = new BufferedOutputStream(new FileOutputStream(fileName));
			out.write(b);
			out.flush();
		}catch (Exception e) {

		}finally {
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		return fileName;
	}

	/**
	 * 将图片处理成圆形
	 *
	 * @param originPath 图片绝对路径 C:/Users/Administrator/Desktop/testImage.png
	 * @param targetPath 图片处理后保存绝对的路径 C:/Users/Administrator/Desktop/pic.png
	 * @return 图片处理后完整路径
	 */
	public static String imageToCircle(String originPath, String targetPath) {
		log.info("将图片处理成圆形:{}", originPath);
		BufferedImage bi1 = null;
		try {
			bi1 = ImageIO.read(new File(originPath));
		} catch (IOException e) {
			throw new RuntimeException("读取图片失败!");
		}
		// 根据需要是否使用 BufferedImage.TYPE_INT_ARGB
		BufferedImage bi2 = null;
		if (bi1 != null) {
			bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(),
				BufferedImage.TYPE_INT_RGB);

			Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1
				.getHeight());

			Graphics2D g2 = bi2.createGraphics();
			g2.setBackground(Color.WHITE);
			g2.fill(new Rectangle(bi2.getWidth(), bi2.getHeight()));
			g2.setClip(shape);
			// 使用 setRenderingHint 设置抗锯齿
			g2.drawImage(bi1, 0, 0, null);
			g2.dispose();

			try {
				ImageIO.write(bi2, "jpg", new File(targetPath));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				throw new RuntimeException("图片写出失败!");
			}
		} else {
			throw new RuntimeException("将图片处理成圆形失败!");
		}
		return targetPath;
	}

	/**
	 * 去除图片白色背景
	 * 注意:要保存为.png格式
	 *
	 * @param originPath 图片绝对路径 C:/Users/Administrator/Desktop/testImage.png
	 * @param targetPath 图片处理后保存绝对的路径 C:/Users/Administrator/Desktop/pic.png
	 * @return 图片处理后完整路径
	 */
	public static String wipeWhiteBackground(String originPath, String targetPath) {
		log.info("去除图片白色背景:{}", originPath);
		File file = new File(originPath);
		InputStream is;
		try {
			is = new FileInputStream(file);
			// 如果是MultipartFile类型,那么自身也有转换成流的方法:is = file.getInputStream();
			BufferedImage bi = ImageIO.read(is);
			ImageIcon imageIcon = new ImageIcon((Image) bi);
			BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
				BufferedImage.TYPE_4BYTE_ABGR);
			Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
			g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
			int alpha = 0;
			for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
				for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
					int rgb = bufferedImage.getRGB(j2, j1);
					int R = (rgb & 0xff0000) >> 16;
					int G = (rgb & 0xff00) >> 8;
					int B = (rgb & 0xff);
					if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) {
						rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
					}
					bufferedImage.setRGB(j2, j1, rgb);
				}
			}
			g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
			ImageIO.write(bufferedImage, "png", new File(targetPath));
		} catch (Exception e) {
			throw new RuntimeException("去除图片白色背景失败!");
		}
		return targetPath;
	}

}

下载

package org.springblade.common.utils;

import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 文件工具类
 *
 * @author wq
 * @date 2021/4/27 17:46
 */
@Slf4j
public class FileUtils {

	/**
	 * 下载 及 预览
	 *
	 * @param filePath 需要下载的文件绝对路径
	 * @param response response
	 * @param isOnLine 下载:false  预览:true
	 * @param fileName 输出的文件名
	 */
	public static void download(String filePath, HttpServletResponse response,
						 boolean isOnLine, String fileName) {
		log.info("文件位置:{}", filePath);
		File f = new File(filePath);
		if (!f.exists()) {
			try {
				response.sendError(404, "File not found!");
			} catch (IOException e) {
				throw new RuntimeException("文件不存在!");
			}
			return;
		}
		BufferedInputStream br = null;
		try {
			br = new BufferedInputStream(new FileInputStream(f));
		} catch (FileNotFoundException e) {
			throw new RuntimeException("文件未找到!");
		}
		byte[] bs = new byte[1024];
		int len = 0;
		response.reset(); // 非常重要
		if (isOnLine) { // 在线打开方式
			URL u = null;
			try {
				u = new URL("file:///" + filePath);
			} catch (MalformedURLException e) {
				throw new RuntimeException("预览文件路径有误!");
			}
			String contentType = null;
			try {
				contentType = u.openConnection().getContentType();
			} catch (IOException e) {
				throw new RuntimeException("预览文件ContentType有误!");
			}
			response.setContentType(contentType);
			response.setHeader("Content-Disposition", "inline;filename="
				+ fileName);
			// 文件名应该编码成utf-8,注意:使用时,我们可忽略这句
		} else {
			// 纯下载方式
//			response.setContentType("application/pdf");
//			response.setContentType("application/x-msdownload");
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename="
				+ fileName);
		}
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			while ((len = br.read(bs)) > 0) {
				out.write(bs, 0, len);
			}
			out.flush();
			out.close();
			br.close();
		} catch (IOException e) {
			throw new RuntimeException("下载失败,请稍后重试!");
		}
	}

}

base64

package org.springblade.common.utils;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;

/**
 * Base64工具类
 *
 * @author wq
 * @date 2021/4/28 10:19
 */
public class Base64Utils {

    /**
     * 将图片文件转换成base64字符串,参数为该图片的路径
     *
     * @param imageFile
     * @return java.lang.String
     */
    public String ImageToBase64(String imageFile) {
        InputStream in = null;
        byte[] data = null;

        // 读取图片字节数组
        try {
            in = new FileInputStream(imageFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();

        if (data != null) {
            return "data:image/jpeg;base64," + encoder.encode(data);// 返回Base64编码过的字节数组字符串
        }
        return null;
    }

    /**
     * 将base64解码成图片并保存在传入的路径下
     * 第一个参数为base64 ,第二个参数为路径
     *
     * @param base64, imgFilePath
     * @return boolean
     */
    public boolean Base64ToImage(String base64, String imgFilePath) {
        // 对字节数组字符串进行Base64解码并生成图片
        if (base64 == null) // 图像数据为空
		{
			return false;
		}
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(base64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    /**
     * 用来测试工具类是否成功
     *
     * @param args
     * @return void
     */
    public static void main(String[] args) {
        String path = "C:/Users/Administrator/Desktop/头像.jpg";
        Base64Utils base64Utils = new Base64Utils();
        String s = base64Utils.ImageToBase64(path);
        System.out.println(s);


        String newpath = "C:/Users/Administrator/Desktop/";
		String s1 = decodeBase64(s, newpath, "jpg", false);
		System.out.println("s1 = " + s1);
    }

	public static String decodeBase64(String base64,String filePath,String suffix,boolean isSafe){
		if(StringUtils.isBlank(base64)||StringUtils.isBlank(filePath)||StringUtils.isBlank(suffix)){
			throw new NullPointerException();
		}
		OutputStream out=null;
		String fileName=null;
		try {
			byte[] b=new byte[2048];
			if(isSafe){
				java.util.Base64.Decoder decoder = java.util.Base64.getUrlDecoder();
				b = decoder.decode(base64);
			}else{
				BASE64Decoder decoder = new BASE64Decoder();
				b = decoder.decodeBuffer(base64.substring(base64.indexOf(",") + 1));
			}
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			File file=new File(filePath);
			if(!file.exists()){
				file.mkdirs();
			}
			fileName=filePath+System.currentTimeMillis()+"."+suffix;
			out = new BufferedOutputStream(new FileOutputStream(fileName));
			out.write(b);
			out.flush();
		}catch (Exception e) {

		}finally {
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		return fileName;
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值