package com.pingpang.util;

import java.awt.image.BufferedImage;

//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Base64;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageBase64Converter {
	
	//日志操作
    private static Logger logger = LoggerFactory.getLogger(ImageBase64Converter.class);
		
    public static void main(String[] args) {
    	System.out.println(ImageBase64Converter.convertFileToBase64("C:\\Users\\dell\\git\\PingPangChat2\\ChatWebClient\\static\\upload\\79a3c5734d0f47eeaa0ec9fe8b1c1c56.jpeg"));
    	System.out.println(ImageBase64Converter.convertFileToBase64Img("C:\\Users\\dell\\git\\PingPangChat2\\ChatWebClient\\static\\upload\\79a3c5734d0f47eeaa0ec9fe8b1c1c56.jpeg"));
    	System.out.println(ImageBase64Converter.convertFileToBase64Nio("C:\\Users\\dell\\git\\PingPangChat2\\ChatWebClient\\static\\upload\\79a3c5734d0f47eeaa0ec9fe8b1c1c56.jpeg"));
        String img=" ";
        String path="C:\\Users\\dell\\git\\PingPangChat2\\ChatWebClient\\static\\upload\\";
        //ImageBase64Converter.convertBase64ToFile(img, path, UUID.randomUUID()+".jpeg");
        ImageBase64Converter.convertBase64ToFileImg(img, path, UUID.randomUUID()+"123.jpeg");
    }
    
    /**
     * Nio
     * @param imgPath     
     */
	public static String convertFileToBase64Nio(String imgPath) {
		try {
			long currentTime = System.currentTimeMillis();
			String imageType = imgPath.substring(imgPath.lastIndexOf(".") + 1);
			FileInputStream in = new FileInputStream(imgPath);
			logger.info("路径:"+imgPath);
        	logger.info("文件大小（字节）="+in.available());
        	ByteArrayOutputStream out =new ByteArrayOutputStream();
			FileChannel inChannel = in.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			int length=-1;
			while ((length=inChannel.read(buffer)) != -1) {
				// 数据组合.
				out.write(buffer.array(),0,length);
				buffer.clear();
			}
			inChannel.close();
			in.close();
			String base64Str = Base64.getEncoder().encodeToString(out.toByteArray());
			out.close();
			logger.info("耗时:"+String.valueOf(System.currentTimeMillis()-currentTime));
			return "data:image/" + imageType + ";base64," + base64Str;
		} catch (Exception e) {
			logger.error("图片转64失败",e);
		}
		return "";
	}
    
    /**
     * ImageIO
     *
     * @param imgPath     
     */
    public static String convertFileToBase64Img(String imgPath) {
    	long currentTime=System.currentTimeMillis();
    	byte[] data = null;
        String imageType="";
        // 读取图片字节数组
        try {
        	imageType=imgPath.substring(imgPath.lastIndexOf(".")+1);
        	FileInputStream  in = new FileInputStream(imgPath);
        	logger.info("路径:"+imgPath);
        	logger.info("文件大小（字节）="+in.available());
        	ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(ImageIO.read(in), imageType, stream);
            data=stream.toByteArray(); 	
            stream.close();
            in.close();
        } catch (IOException e) {
        	logger.error("图片转64失败",e);
        }
        String base64Str = Base64.getEncoder().encodeToString(data);
        //logger.info(base64Str);
        logger.info("耗时:"+String.valueOf(System.currentTimeMillis()-currentTime));
        return "data:image/"+imageType+";base64,"+base64Str;
    }
    
    /**
     * ImageIO
     */
    public static void convertBase64ToFileImg(String fileBase64String, String filePath, String fileName) {
    	try {
    		long currentTime=System.currentTimeMillis();
    		File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            byte[] bfile =Base64.getDecoder().decode(fileBase64String);
            ByteArrayInputStream inputStream=new ByteArrayInputStream(bfile);
            BufferedImage bi=ImageIO.read(inputStream);
            ImageIO.write(bi, fileName.substring(fileName.indexOf(".")+1), new File(filePath + File.separator + fileName));
    	    inputStream.close();
    	    logger.info("耗时:"+String.valueOf(System.currentTimeMillis()-currentTime)); 
    	}catch (Exception e) {
    		logger.error("保存图片失败",e);
		}
    }
    
    /**
     * FileInputStream
     *
     * @param imgPath     
     */
    public static String convertFileToBase64(String imgPath) {
    	long currentTime=System.currentTimeMillis();
        byte[] data = null;
        String imageType="";
        // 读取图片字节数组
        try {
        	imageType=imgPath.substring(imgPath.lastIndexOf(".")+1);
            InputStream in = new FileInputStream(imgPath);
            logger.info("路径:"+imgPath);
            logger.info("文件大小（字节）="+in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
        	logger.error("图片转64失败",e);
        }
        String base64Str = Base64.getEncoder().encodeToString(data);
        //logger.info(base64Str);
        logger.info("耗时:"+String.valueOf(System.currentTimeMillis()-currentTime));
        return "data:image/"+imageType+";base64,"+base64Str;
    }

    /**
     * FileInputStream
     */
    public static void convertBase64ToFile(String fileBase64String, String filePath, String fileName) {
    	long currentTime=System.currentTimeMillis();
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            byte[] bfile =Base64.getDecoder().decode(fileBase64String);
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
        	logger.error("保存图片失败",e);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                	logger.error("保存图片失败",e1);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    logger.error("保存图片失败",e1);
                }
            }
            logger.info("耗时:"+String.valueOf(System.currentTimeMillis()-currentTime)); 
        }
    }

}
