【java基础】 图片和base64字符串互转

2019-07-25 14:34:22 浏览数 (1)

1、代码

代码语言:javascript复制
package com.zsxy.util;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;

import org.junit.Test;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 *  图片与base64字符串互转
 */
@SuppressWarnings("all")
public class Pic_transform {

	@Test
	public void test01(){
		String data = GetImageStrFromPath("D:///24642e2a87de4b12039c9bdeb80e708b.jpg");
		System.out.println(data);
		GenerateImage(data);
		
	}
	public static String getURLImage(String imageUrl,String host,String referer,String cookie){  
        URL url;
        String data = null ;
		try {
			url = new URL(imageUrl);
		
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
        conn.addRequestProperty("Host",host);
        conn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        conn.addRequestProperty("Accept","image/png,image/*;q=0.8,*/*;q=0.5");
        conn.addRequestProperty("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        conn.addRequestProperty("Accept-Encoding","gzip, deflate");
        conn.addRequestProperty("Referer",referer);
        conn.addRequestProperty("Cookie",cookie);
        conn.addRequestProperty("Connection","keep-alive");
        conn.addRequestProperty("Pragma","no-cache");
        conn.addRequestProperty("Cache-Control","no-cache");
        conn.setRequestMethod("GET");  
        conn.setConnectTimeout(20 * 1000);
        InputStream input = conn.getInputStream();  

        //data = GetImageStrByInPut(input) ;
        data = GetImageStrFromUrl(input);
//        GenerateImage(data);


	
   
	} catch (MalformedURLException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
		return data;  
	}
		
    	  /** 
         * 璇诲彇杈撳叆娴�,杞崲涓築ase64瀛楃涓� 
         * @param input 
         * @return 
         */  
        public static String GetImageStrByInPut(InputStream in) {
        	String imgBase64 = "";
        	try {
        		BufferedImage bufferedImage = ImageIO.read(in);
        		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        		ImageIO.write(bufferedImage,"jpg",outputStream);
        		byte[] outByteArray = outputStream.toByteArray();
        		BASE64Encoder encoder = new BASE64Encoder();
        		Thread.sleep(1000);
        		imgBase64 = encoder.encode(outByteArray);
        	}catch(IllegalArgumentException ie){
//        		ie.printStackTrace();
        		System.out.println("IllegalArgumentException");
        		 GetImageStrByInPut(in);
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        	//return imgBase64.replace("[ ] ","").replace(" ", "").replaceAll("r|n","").trim();
        	return imgBase64;
        }
        /**
         * 测试,base64字符串转图片
         * @param imgStr
         * @return
         */
        public static boolean GenerateImage(String imgStr) {  
            if (imgStr == null) // 图像数据为空  
                return false;  
            BASE64Decoder decoder = new BASE64Decoder();  
            try {  
                // Base64解码  
                byte[] b = decoder.decodeBuffer(imgStr);  
                for (int i = 0; i < b.length;   i) {  
                    if (b[i] < 0) {// 调整异常数据  
                        b[i]  = 256;  
                    }  
                }  
                // 生成jpeg图片  
                String imgFilePath = "d://222.jpg";  
                OutputStream out = new FileOutputStream(imgFilePath);  
                out.write(b);  
                out.flush();  
                out.close();  
                return true;  
            } catch (Exception e) {  
                return false;  
            }  
        } 
        /**
         * 本地图片转base64字符串
         * @param imgPath
         * @return
         */
        public static String GetImageStrFromPath(String imgPath) {  
            InputStream in = null;  
            byte[] data = null;  
            // 读取图片字节数组  
            try {  
                in = new FileInputStream(imgPath);  
                data = new byte[in.available()];  
                in.read(data);  
                in.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            // 对字节数组Base64编码  
            BASE64Encoder encoder = new BASE64Encoder();  
            // 返回Base64编码过的字节数组字符串  
            return encoder.encode(data);  
        }
        /**
         * 流转base64字符串
         * @param inStream
         * @return
         */
        public static String GetImageStrFromUrl(InputStream inStream) {  
            byte[] data = null;  
            try {  
                data = new byte[inStream.available()];  
                inStream.read(data);  
                inStream.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            // 对字节数组Base64编码  
            BASE64Encoder encoder = new BASE64Encoder();  
            // 返回Base64编码过的字节数组字符串  
            return encoder.encode(data);  
        }
        
  }

0 人点赞