JSON傳輸圖片幫助類

JSON傳輸圖片幫助類

(爲什麼這樣做,是因爲圖片,通過IO操作之後獲取的是byte[]字節數組,而JSON傳輸用的是String,所以需要轉換爲String,但是直接轉換的話會因爲,字符的編碼不同而導致,得不到最終的效果)

所以需要到由圖片到String的幫助類
貼上代碼

package org.helper;

import java.io.FileInputStream;
import java.io.IOException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 * Description:用此類將圖片轉換爲字符串,以便將圖片封裝爲JSON進行傳輸
 * @author 河伯
 * @Date 2014-05-27
 * @version 1.0
 * */
public class ImgHelper {
    
    /**
     * TODO:將byte數組以Base64方式編碼爲字符串
     * @param bytes 待編碼的byte數組
     * @return 編碼後的字符串
     * */
    public static String encode(byte[] bytes){
        return new BASE64Encoder().encode(bytes);
    }
    
    /**
     * TODO:將以Base64方式編碼的字符串解碼爲byte數組
     * @param encodeStr 待解碼的字符串
     * @return 解碼後的byte數組
     * @throws IOException 
     * */
    public static byte[] decode(String encodeStr) throws IOException{
        byte[] bt = null;  
        BASE64Decoder decoder = new BASE64Decoder();  
        bt = decoder.decodeBuffer(encodeStr);
        return bt;
    }
    
    /**
     * TODO:將兩個byte數組連接起來後,返回連接後的Byte數組
     * @param front 拼接後在前面的數組
     * @param after 拼接後在後面的數組
     * @return 拼接後的數組
     * */
    public static byte[] connectBytes(byte[] front, byte[] after){
        byte[] result = new byte[front.length + after.length];
        System.arraycopy(front, 0, result, 0, after.length);
        System.arraycopy(after, 0, result, front.length, after.length);
        return result;
    }
    
    /**
     * TODO:將圖片以Base64方式編碼爲字符串
     * @param imgUrl 圖片的絕對路徑(例如:D:\\jsontest\\abc.jpg)
     * @return 編碼後的字符串
     * @throws IOException 
     * */
    public static String encodeImage(String imgUrl) throws IOException{
        FileInputStream fis = new FileInputStream(imgUrl);
        byte[] rs = new byte[fis.available()];
        fis.read(rs);
        fis.close();
        return encode(rs);
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        String str;
        try {
            str = encodeImage("E:\\yunifang_img\\1.jpg");
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章