java 图片转换工具

package com.sicdt.sicsign.web.utils;


import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.apache.commons.io.FileUtils;
import org.bouncycastle.util.encoders.Base64Encoder;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;

public class MyImgUtils {
    
    /**
     * <br>描 述: 将图片BASE64字符串转为二进制数组
     * <br>作 者: 七脉
     * @param base64 new Image();img.src或canvas.toDataURL("image/png")
     * @return
     * @throws IOException
     */
    @SuppressWarnings("restriction")
    public static byte[] imgBase64ToBytes(String base64) {
        sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        //因为参数base64来源不一样,需要将附件数据替换清空掉。如果此入参来自canvas.toDataURL("image/png");
        base64 = base64.replaceAll("data:image/png;base64,", "");
        //base64解码并转为二进制数组
        byte[] bytes = null;
        try {
            bytes = decoder.decodeBuffer(base64);
            for (int i = 0; i < bytes.length; ++i) {  
                if (bytes[i] < 0) {// 调整异常数据  
                    bytes[i] += 256;  
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }
    
    /**
     * <br>描 述: 图片字节数组转base64
     * <br>作 者: shizhenwei 
     * <br>历 史: (版本) 作者 时间 注释
     * @return
     */
    @SuppressWarnings("restriction")
    public static String bytesToImgBase64(byte[] bytes){
        sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
        return encoder.encode(bytes);
    }
    
    /**
     * 
     * <br>描 述:    图片/文件转二进制数组,这个方法有很多,只写一个
     * <br>作 者: 七脉
     * @param imgPath 图片路径
     * @return
     * @throws FileNotFoundException
     */
    public static byte[] imgToBytes(String imgPath) {
        File file = new File(imgPath);
        BufferedImage bi = null;
        ByteArrayOutputStream baos = null;
        try {
            //文件使用其他工具
            bi = ImageIO.read(file);
            baos = new ByteArrayOutputStream();
            int index = imgPath.lastIndexOf(".");
            String format = imgPath.substring(index+1);
            ImageIO.write(bi, format, baos);
            byte[] bytes = baos.toByteArray();
            baos.close();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 
     * <br>描 述:    将二进制转换为图片
     * <br>作 者: 七脉
     * @param outPath 将图片输出到哪里
     * @param savePath 保存位置
     */
    public static void bytesToImg(byte[] bytes,String savePath){
        ByteArrayInputStream baos = new ByteArrayInputStream(bytes);
        try {
            BufferedImage bi = ImageIO.read(baos);
            File file = new File(savePath);
            ImageIO.write(bi, "png", file);
            baos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * <br>描 述:    图片二进制数组转PDF二进制数组
     * <br>作 者: 七脉
     * @param imgBytes 图片二进制数组
     * @return
     */
    public static byte[] imgBytesToPdfBytes(byte[] imgBytes){
            byte[] bytes = null;
            Document document = new Document();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                PdfWriter.getInstance(document, baos);
                // 设置文档的大小
                document.setPageSize(PageSize.A4);
                // 打开文档
                document.open();
                // 读取一个图片
                Image image = Image.getInstance(imgBytes);
                float imageWidth = image.getScaledWidth();
                int i = 0;
                while (imageWidth > 600) {
                    image.scalePercent(100 - i);
                    i++;
                    imageWidth = image.getScaledWidth();
                }
                image.setAlignment(Image.ALIGN_CENTER);
                // 插入一个图片
                document.add(image);
                //转二进制数组
                bytes = baos.toByteArray();
                return bytes;
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(null!=baos){
                    try {
                        baos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(null!=document){
                    document.close();
                }
            }
            return bytes;
    }
    
    
    /**
     * 
     * <br>描 述:    二进制转文件,什么样的二进制转什么样的文件
     * <br>作 者: 七脉 
     * @param bytes 二进制数组
     * @param savePath 文件保存路径
     */
    public static void byteArrayToFile(byte[] bytes,String savePath){
        try {
            FileUtils.writeByteArrayToFile(new File(savePath), bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * <br>描 述: 去除图片背景,转透明图
     * <br>作 者: shizhenwei 
     * <br>历 史: (版本) 作者 时间 注释
     * @param is
     * @return
     */
    public static byte[] toTransparency(InputStream is) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            BufferedImage bi = ImageIO.read(is);
            java.awt.Image image = (java.awt.Image) bi;
            ImageIcon imageIcon = new ImageIcon(image);
            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", byteArrayOutputStream);// 直接输出文件
        } catch (Exception e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toByteArray();
    }
    
}

 

posted @ 2017-11-15 16:12  七脉  阅读(1747)  评论(0编辑  收藏  举报