package com.nationalelectric.greenH5.identityAuth.util; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Base64; import javax.imageio.ImageIO; import javax.imageio.stream.FileImageOutputStream; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; import sun.misc.BASE64Decoder; public class PhotoUtil { /** * base64转图片并保存到本地 * @param baseStr base64编码 * @param imagePath 图片保存路径 * @return */ public static boolean base64ChangeImage(String baseStr,String imagePath){ if (baseStr == null){ return false; } BASE64Decoder decoder = new BASE64Decoder(); try { // 解密 byte[] b = decoder.decodeBuffer(baseStr); // 处理数据 for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } OutputStream out = new FileOutputStream(imagePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } /** * 指定图片宽度和高度和压缩比例对图片进行压缩 * * @param imgsrc * 源图片地址 * @param imgdist * 目标图片地址 * @param widthdist * 压缩后图片的宽度 * @param heightdist * 压缩后图片的高度 * @param rate * 压缩的比例 */ public static void reduceImg(String imgsrc, String imgdist, Float rate) { int widthdist = 0; int heightdist = 0; try { File srcfile = new File(imgsrc); // 检查图片文件是否存在 if (!srcfile.exists()) { System.out.println("文件不存在"); } // 如果比例不为空则说明是按比例压缩 if (rate != null && rate > 0) { //获得源图片的宽高存入数组中 int[] results = getImgWidthHeight(srcfile); if (results == null || results[0] == 0 || results[1] == 0) { return; } else { //按比例缩放或扩大图片大小,将浮点型转为整型 widthdist = (int) (results[0] * rate); heightdist = (int) (results[1] * rate); } } // 开始读取文件并进行压缩 Image src = ImageIO.read(srcfile); // 构造一个类型为预定义图像类型之一的 BufferedImage BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB); //绘制图像 getScaledInstance表示创建此图像的缩放版本,返回一个新的缩放版本Image,按指定的width,height呈现图像 //Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。 tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null); //创建文件输出流 FileOutputStream out = new FileOutputStream(imgdist); //将图片按JPEG压缩,保存到out中 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); //关闭文件输出流 out.close(); if(srcfile.length()>10*1024){ reduceImg(imgsrc,imgdist,rate); } } catch (Exception ef) { ef.printStackTrace(); } } /** * 获取图片宽度和高度 * * @param * @return 返回图片的宽度 */ public static int[] getImgWidthHeight(File file) { InputStream is = null; BufferedImage src = null; int result[] = { 0, 0 }; try { // 获得文件输入流 is = new FileInputStream(file); // 从流里将图片写入缓冲图片区 src = ImageIO.read(is); result[0] =src.getWidth(null); // 得到源图片宽 result[1] =src.getHeight(null);// 得到源图片高 is.close(); //关闭输入流 } catch (Exception ef) { ef.printStackTrace(); } return result; } /** * * @param path * @return String * @description 将文件转base64字符串 * @date 2018年3月20日 * @author changyl * File转成编码成BASE64 */ public static String fileToBase64(String path) { String base64 = null; InputStream in = null; try { File file = new File(path); in = new FileInputStream(file); byte[] bytes=new byte[(int)file.length()]; in.read(bytes); base64 = Base64.getEncoder().encodeToString(bytes); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return base64; } public static byte[] getByteByPic(String imageUrl) throws IOException{ File imageFile = new File(imageUrl); InputStream inStream = new FileInputStream(imageFile); BufferedInputStream bis = new BufferedInputStream(inStream); BufferedImage bm = ImageIO.read(bis); ByteArrayOutputStream bos = new ByteArrayOutputStream(); String type = imageUrl.substring(imageUrl.length() - 3); ImageIO.write(bm, type, bos); bos.flush(); byte[] data = bos.toByteArray(); return data; } /** * 将图片压缩到指定大小以内 * * @param srcImgData 源图片数据 * @param maxSize 目的图片大小 * @return 压缩后的图片数据 */ public static byte[] compressUnderSize(byte[] srcImgData, long maxSize) { double scale = 0.9; byte[] imgData = Arrays.copyOf(srcImgData, srcImgData.length); if (imgData.length > maxSize) { do { try { imgData = compress(imgData, scale); } catch (IOException e) { throw new IllegalStateException("压缩图片过程中出错,请及时联系管理员!", e); } } while (imgData.length > maxSize); } return imgData; } /** * 按照 宽高 比例压缩 * * @param imgIs 待压缩图片输入流 * @param scale 压缩刻度 * @param out 输出 * @return 压缩后图片数据 * @throws IOException 压缩图片过程中出错 */ public static byte[] compress(byte[] srcImgData, double scale) throws IOException { BufferedImage bi = ImageIO.read(new ByteArrayInputStream(srcImgData)); int width = (int) (bi.getWidth() * scale); // 源图宽度 int height = (int) (bi.getHeight() * scale); // 源图高度 Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH); BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.setColor(Color.RED); g.drawImage(image, 0, 0, null); // 绘制处理后的图 g.dispose(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ImageIO.write(tag, "JPEG", bOut); return bOut.toByteArray(); } //byte数组到图片 public static void byte2image(byte[] data,String path){ if(data.length<3||path.equals("")) return; try{ FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path)); imageOutput.write(data, 0, data.length); imageOutput.close(); System.out.println("Make Picture success,Please find image in " + path); } catch(Exception ex) { System.out.println("Exception: " + ex); ex.printStackTrace(); } } public static void main(String[] args) throws IOException { // PhotoUtil.reduceImg("C:\\Users\\Feb\\Desktop\\test.jpg", "C:\\Users\\Feb\\Desktop\\test1.jpg", 1f); long timeStart = System.currentTimeMillis(); String imgLocalUrl = "C:\\Users\\Feb\\Desktop\\test.jpg"; byte[] imgBytes = getByteByPic(imgLocalUrl); byte[] resultImg = compressUnderSize(imgBytes,10 * 1024); byte2image(resultImg,"C:\\Users\\Feb\\Desktop\\test1.jpg"); long timeEnd = System.currentTimeMillis(); System.out.println("耗时:"+ (timeEnd - timeStart)); } }