引入依赖jar
<dependency> <groupId>com.drewnoakes</groupId> <artifactId>metadata-extractor</artifactId> <version>2.8.1</version> </dependency>
编写测试类
package net.hp; import cn.hutool.core.date.DatePattern; import com.alibaba.fastjson.JSON; import com.drew.imaging.ImageMetadataReader; import com.drew.metadata.Directory; import com.drew.metadata.Metadata; import com.drew.metadata.Tag; import com.sun.xml.internal.ws.api.addressing.WSEndpointReference; import lombok.extern.slf4j.Slf4j; import net.coobird.thumbnailator.Thumbnails; import net.hp.common.model.DTO.request.door.callback.DoorCallbackDataDTO; import net.hp.common.model.DTO.request.door.callback.DoorQrcodeCallbackDataDTO; import net.hp.common.utils.DateUtils; import net.hp.common.utils.ImageUtil; import net.hp.common.utils.R; import org.junit.jupiter.api.Test; import sun.misc.BASE64Encoder; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.text.ParseException; import java.util.Date; import java.util.UUID; @Slf4j public class TestCallback { private static final String saveRootPath = "E://statices/"; // 获取文件扩展信息,判定是否有旋转信息 // 3.jpg Orientation = Right side, top (Rotate 90 CW)[Exif IFD0] Orientation - Right side, top (Rotate 90 CW) private void outExt(File file) { try { Metadata metadata = ImageMetadataReader.readMetadata(file); for (Directory directory : metadata.getDirectories()) { for (Tag tag : directory.getTags()) { System.out.format("[%s] - %s = %s", directory.getName(), tag.getTagName(), tag.getDescription()); System.out.println(); /*if (tag.getTagName().equals("Orientation")) { Thumbnails.of(file).scale(0.9).toFile(file); break; }*/ } if (directory.hasErrors()) { for (String error : directory.getErrors()) { System.err.format("ERROR: %s", error); } } } } catch (Exception e) { System.out.println(e.toString()); } } @Test public void t() { try { String imgBase64 = this.imageToBase64("C:\\Users\\zf-w00045\\Desktop\\4.jpg"); BufferedImage bi = ImageUtil.base64ToBufferedImage(imgBase64); //File file = new File("C:\\Users\\zf-w00045\\Desktop\\4.jpg"); //R checkImageR = uniubiCheckImage(ImageIO.read(file)); R checkImageR = uniubiCheckImage(bi); if (checkImageR.hasError()) { return; } BufferedImage bufferedImage = (BufferedImage) checkImageR.get("data"); String fileName = "out.png"; String filePath = "image/faceimg/" + DateUtils.format(new Date(), "yyyyMMdd") + "/" + fileName; String saveFilePath = saveRootPath + filePath; File saveFile = new File(saveFilePath); if (!saveFile.exists()) { saveFile.mkdirs(); } ImageIO.write(bufferedImage, "PNG", saveFile); } catch (Exception e) { e.printStackTrace(); } } /** * 返回处理过的bufferImage * * @param bufferedImage * @return */ private static R uniubiCheckImage(BufferedImage bufferedImage) { R r = new R(); long s = System.currentTimeMillis(); try { String fileName = UUID.randomUUID().toString().replace("-", "") + "_tmp.png"; String fileFolder = "image/faceimg/" + DateUtils.format(new Date(), "yyyyMMdd"); String saveFileFloder = saveRootPath + fileFolder; String filePath = fileFolder + "/" + fileName; String saveFilePath = saveRootPath + filePath; File folder = new File(saveFileFloder); if (!folder.exists()) { folder.mkdirs(); } try { boolean hasOrientation = false; String tmpFileName = UUID.randomUUID().toString().replace("-", "") + ".png"; File tempFile = new File(saveFileFloder + "/" + tmpFileName); ImageIO.write(bufferedImage, "PNG", tempFile); Metadata metadata = ImageMetadataReader.readMetadata(tempFile); for (Directory directory : metadata.getDirectories()) { for (Tag tag : directory.getTags()) { System.out.format("[%s] - %s = %s", directory.getName(), tag.getTagName(), tag.getDescription()); System.out.println(); if (tag.getTagName().equals("Orientation")) { hasOrientation = true; System.out.println("需要旋转"); Thumbnails.of(tempFile).scale(0.9).toFile(tempFile); break; } } if (hasOrientation) { break; } if (directory.hasErrors()) { for (String error : directory.getErrors()) { System.err.format("ERROR: %s", error); } } } if (hasOrientation) { bufferedImage = ImageIO.read(tempFile); // tempFile.delete(); } } catch (Exception e) { System.out.println(e.toString()); } int imgHeight = bufferedImage.getHeight(); int imgWidth = bufferedImage.getWidth(); // 文件小于112, 则失败 if (!(imgHeight >= 112 && imgWidth >= 112)) { r.putErrorMsg("图片宽高至少112"); log.info(r.getErrorMsg()); return r; } // 文件超出1024p, 则缩小 File file = null; if (imgHeight >= 1024 || imgWidth >= 1024) { int limit = 1000; int newHeight = 0; int newWidth = 0; if (imgHeight >= imgWidth) { newHeight = limit; // 图高较大, 宽较小; 固定高this.height, 计算宽 newWidth = imgWidth / (imgHeight / limit); } else if (imgHeight < imgWidth) { newWidth = limit; // 图宽较大, 高较小; 固定宽this.width, 计算高 newHeight = imgHeight / (imgWidth / limit); } log.info("图片超出1024p, 原图高:{}, 宽:{}, 处理后高:{}, 宽:{}", imgHeight, imgWidth, newHeight, newWidth); file = new File(saveFilePath); if (!file.exists()) { file.createNewFile(); } Thumbnails.of(bufferedImage).size(newWidth, newHeight).toFile(saveFilePath); } else { file = new File(saveFilePath); if (!file.exists()) { file.createNewFile(); } ImageIO.write(bufferedImage, "PNG", file); } // 文件超出2M,则循环压缩 while (true) { if (file.length() / 1024 > 1500) { log.info("图片超出2M 大小:{}KB, 执行压缩.", (file.length() / 1024)); Thumbnails.of(file).scale(0.8f).toFile(file); continue; } else { break; } } bufferedImage = ImageIO.read(file); r.put("data", bufferedImage); //file.delete(); log.info("宇泛图片处理 用时:{}", (System.currentTimeMillis() - s)); } catch (IOException e) { r.putErrorMsg("宇泛图片处理异常"); log.error("fail -> " + r.getErrorMsg(), e); } return r; } private void aa(DoorCallbackDataDTO baseDTO) { System.out.println(JSON.toJSON(baseDTO)); } /** * 图片转Base64 * * @param imgPath * @return */ protected String imageToBase64(String imgPath) { ByteArrayOutputStream data = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; // 读取图⽚字节数组d try { InputStream in = new FileInputStream(imgPath); int len = -1; while ((len = in.read(bytes)) != -1) { data.write(bytes, 0, len); } in.close(); } catch (IOException e) { e.printStackTrace(); } // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64编码过的字节数组字符串 String base64 = encoder.encode(data.toByteArray()); return base64; } }
标签:String,bufferedImage,信息,System,获取,file,new,import,图片 From: https://www.cnblogs.com/eason-d/p/16706591.html