图片工具类

项目用的图片工具类  包括复制图片 压缩图片 base64互转图片  bate互转图片

import com.google.common.collect.Maps;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Map;

/**
 * 图片通用工具类
 * Created by wulin
 */
public class ImageUtils {
    private static Logger logger = LoggerFactory.getLogger(ImageUtils.class);


    /**
     * 复制图片
     *
     * @param fromPath 原图片路径
     * @param toPath   复制图片的路径
     * @return
     */
    public static boolean copyImage(String fromPath, String toPath) {
        return copyImage(fromPath, toPath, 1);
    }

    /**
     * 复制图片
     *
     * @param fromPath 原图片路径
     * @param toPath   复制图片的路径
     * @param multiple 图片放大缩小的倍数, 长宽等比例放大缩小
     * @return
     */
    public static boolean copyImage(String fromPath, String toPath, Integer multiple) {
        try {
            fromPath = StringUtils.convertPath(java.net.URLDecoder.decode(fromPath, "UTF-8"));
            toPath = StringUtils.convertPath(java.net.URLDecoder.decode(toPath, "UTF-8"));
            String suffixName = toPath.substring(toPath.lastIndexOf(".") + 1);
            toPath = StringUtils.convertPath(toPath);
            File file = new File(fromPath);
            if (file == null || !file.isFile()) {
                return false;
            } else {
                //要拷贝的图片
                Image image = ImageIO.read(file);
                int width = image.getWidth(null);   //图片原宽度
                int height = image.getHeight(null); //图片原高度
                Map
   
   
    
     map = calcRatio(width, height, multiple);
                int toImgWidth = map.get("width");   //图片压缩后的宽度
                int toImgHeight = map.get("height"); //图片压缩后的高度
                BufferedImage imageTag = new BufferedImage(toImgWidth, toImgHeight, BufferedImage.TYPE_INT_RGB);
                imageTag.getGraphics().drawImage(image, 0, 0, toImgWidth, toImgHeight, null);

                mkDirs(toPath);

                ImageIO.write(imageTag, suffixName, new File(toPath));
            }
        } catch (FileNotFoundException fe) {
            fe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 按指定比例计算图片压缩后的宽高度
     *
     * @param width    原宽度
     * @param height   原高度
     * @param multiple 压缩倍数  压缩后的值为  原高度/multiple 或 原宽度/multiple
     * @return
     */
    public static Map
    
    
     
      calcRatio(Integer width, Integer height, float multiple) {
        Map
     
     
      
       map = Maps.newHashMap();
        if (multiple == 1) {
            map.put("width", width);
            map.put("height", height);
            return map;
        }
        float toImgWidth = width;   //图片压缩后的宽度
        float toImgHeight = height; //图片压缩后的高度
        if (width > height)  //如果宽度超过高度以宽度为准来压缩
        {
            toImgWidth = width / multiple;   //图片压缩后的宽度
            toImgHeight = height / (float) (width / toImgWidth); //图片压缩后的高度
        } else {
            toImgHeight = height / multiple; //图片压缩后的高度
            toImgWidth = width / (float) (height / toImgHeight);   //图片压缩后的宽度
        }
        map.put("width", (int) toImgWidth);
        map.put("height", (int) toImgHeight);
        return map;
    }

    /**
     * 指定图片最大宽高度计算图片压缩后的宽高度
     *
     * @param width     原宽度
     * @param height    原高度
     * @param maxWidth  图片宽度最大限制
     * @param maxHeight 图片高度最大限制
     * @return
     */
    public static Map
      
      
       
        calcRatio(Integer width, Integer height, Integer maxWidth, Integer maxHeight) {
        Map
       
       
         map = Maps.newHashMap(); float toImgWidth = width; //图片压缩后的宽度 float toImgHeight = height; //图片压缩后的高度 if (width > height) //如果宽度超过高度以宽度为准来压缩 { if (width > maxWidth) //如果图片宽度超过限制 { toImgWidth = maxWidth; //图片压缩后的宽度 toImgHeight = height / (float) (width / toImgWidth); //图片压缩后的高度 } } else { if (height > maxHeight) { toImgHeight = maxHeight; toImgWidth = width / (float) (height / toImgHeight); } } map.put("width", (int) toImgWidth); map.put("height", (int) toImgHeight); return map; } /** * base64 转图片 * * @param base64String base64字符串 * @param filePath 图片路径 */ public static boolean base64StringToImage(String base64String, String filePath) { try { filePath = StringUtils.convertPath(filePath); return byteToImage(base64StringToByte(base64String), filePath); } catch (Exception e) { e.printStackTrace(); return false; } } /** * byte 转图片 * * @param bytes 图片二进制 * @param filePath 图片路径 */ public static boolean byteToImage(byte[] bytes, String filePath) { if (bytes == null || bytes.length < 1) { return false; } try { filePath = StringUtils.convertPath(java.net.URLDecoder.decode(filePath, "UTF-8")); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); BufferedImage bi1 = ImageIO.read(bais); mkDirs(filePath); File w2 = new File(filePath);//可以是jpg,png,gif格式 ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片,此处不需改动 return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * base64 转 byte * * @param base64String base64字符串 */ public static byte[] base64StringToByte(String base64String) { try { if (StringUtils.isBlank(base64String)) { return null; } if (base64String.startsWith("data:image")) { base64String = base64String.substring(base64String.indexOf("base64,") + "base64,".length()); } byte[] bytes = EncodesUitls.decodeBase64(base64String); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) {// 调整异常数据 bytes[i] += 256; } } return bytes; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将 BufferedImage 转 Base64 * * @param image */ public static byte[] BufferedImage2Byte(BufferedImage image) { try { ByteArrayOutputStream bs = new ByteArrayOutputStream(); ImageOutputStream imOut = ImageIO.createImageOutputStream(bs); ImageIO.write(image, "png", imOut); InputStream in = new ByteArrayInputStream(bs.toByteArray()); byte[] data = new byte[in.available()]; in.read(data); in.close(); bs.close(); bs = null; imOut.close(); imOut = null; return data; } catch (IOException e) { e.printStackTrace(); logger.debug("Exception--" + e.getMessage()); return null; } catch (Exception e) { logger.debug("Exception--" + e.getMessage()); e.printStackTrace(); return null; } } /** * 将 BufferedImage 转 Base64 * * @param image */ public static String BufferedImage2Base64(BufferedImage image) { try { BASE64Encoder encoder = new BASE64Encoder(); return "data:image/png;base64," + EncodesUitls.encodeBase64(BufferedImage2Byte(image)); } catch (Exception e) { logger.debug("Exception--" + e.getMessage()); e.printStackTrace(); return ""; } } /** * 图片 转 byte * * @param file 图片 */ public static byte[] imageToByte(File file) { try { if (file == null || !file.isFile()) { return null; } else { //要拷贝的图片 Image image = ImageIO.read(file); int width = image.getWidth(null); //图片原宽度 int height = image.getHeight(null); //图片原高度 BufferedImage imageTag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); imageTag.getGraphics().drawImage(image, 0, 0, width, height, null); return BufferedImage2Byte(imageTag); } } catch (FileNotFoundException fe) { fe.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 图片 转 Base64 * * @param file 图片 */ public static String imageToBase64(File file) { try { if (file == null || !file.isFile()) { return null; } else { //要拷贝的图片 Image image = ImageIO.read(file); int width = image.getWidth(null); //图片原宽度 int height = image.getHeight(null); //图片原高度 BufferedImage imageTag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); imageTag.getGraphics().drawImage(image, 0, 0, width, height, null); return BufferedImage2Base64(imageTag); } } catch (FileNotFoundException fe) { fe.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } } /** * Byte 转 Base64 * * @param bytes 图片 */ public static String byteToBase64(byte[] bytes) { if (bytes == null || bytes.length < 1) { return null; } try { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); BufferedImage bi1 = ImageIO.read(bais); return BufferedImage2Base64(bi1); } catch (IOException e) { e.printStackTrace(); return null; } } /** * 根据 图片 生产 相应 宽度*高度 缩略图 * * @param imgsrc 原图路径 * @param imgdist 生产缩略图路径 * @param widthdist 生成图片宽度 * @param heightdist 生成图片高度 */ public static void reduceImg(String imgsrc, String imgdist, int widthdist, int heightdist) { try { File srcfile = new File(imgsrc); if (!srcfile.exists()) { return; } Image src = javax.imageio.ImageIO.read(srcfile); BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null); tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_AREA_AVERAGING), 0, 0, null); FileOutputStream out = new FileOutputStream(imgdist); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } 
       
      
      
     
     
    
    
   
   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值