package com.matrix.system.hive.plugin.util; import com.matrix.core.tools.DateUtil; import sun.misc.BASE64Decoder; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Date; import javax.imageio.ImageIO; /** * * @description 照片工具类 * @author Matrix-J * @data 2015年8月6日 下午7:16:18 */ public class ImageUtil { /** * 把图片文件压缩为JPG文件 * @description * @data 2015年8月6日 下午7:17:59 * @author Administrator ·* @author JYY * @param file 源文件 * @param newHeight 新宽度 * @param newWidth 新高度 * @param outputDir 输出目录 * @param outputFileName 输出文件名称 */ public static void compressionImg(File file, int newHeight, int newWidth, String outputDir, String outputFileName) { try { Image img = ImageIO.read(file); // // 判断图片格式是否正确 BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); /* * Image.SCALE_SMOOTH 的缩略算生成缩略图片的平滑度优先级比速度生成的图片质量比较好 但度慢 */ tag.getGraphics().drawImage( img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); FileOutputStream out = new FileOutputStream(outputDir + outputFileName); // JPEGImageEncoder可用于其他图片类型的转 ImageIO.write(tag, "jpg", out); out.close(); } catch (IOException ex) { ex.printStackTrace(); } } public static String base64ToFile(String base64Str, String savePath, String fileName) { String fileDir = DateUtil.dateToString(new Date(), DateUtil.DATE_FORMAT_NO_SPLITE_DD); File dir = new File(savePath + fileDir); if (!dir.isDirectory()) { dir.mkdir(); } BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; String filePathAndName = savePath + fileDir + File.separator + fileName; BASE64Decoder decoder = new BASE64Decoder(); byte[] bfile = new byte[0]; try { bfile = decoder.decodeBuffer(base64Str); file = new File(filePathAndName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bfile); } catch (IOException e) { e.printStackTrace(); } return filePathAndName; } }