图片处理工具类:
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;
@Slf4j
public class ImageUtil {
@Resource
private CustomFileConfig customFileConfig;
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);
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;
}
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 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);
g2.drawImage(bi1, 0, 0, null);
g2.dispose();
try {
ImageIO.write(bi2, "jpg", new File(targetPath));
} catch (IOException e) {
throw new RuntimeException("图片写出失败!");
}
} else {
throw new RuntimeException("将图片处理成圆形失败!");
}
return targetPath;
}
public static String wipeWhiteBackground(String originPath, String targetPath) {
log.info("去除图片白色背景:{}", originPath);
File file = new File(originPath);
InputStream is;
try {
is = new FileInputStream(file);
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;
@Slf4j
public class FileUtils {
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);
} else {
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.*;
public class Base64Utils {
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();
}
BASE64Encoder encoder = new BASE64Encoder();
if (data != null) {
return "data:image/jpeg;base64," + encoder.encode(data);
}
return null;
}
public boolean Base64ToImage(String base64, String imgFilePath) {
if (base64 == null)
{
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
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;
}
}
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;
}
}