java: base 64 문자열 을 그림 으로 변환

1882 단어
package com.mandi.utils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class base64_Img {

    public static void main(String[] args) {
        String str = "";
        str = GetImageStr();
        GenerateImage(str);
    }

    //      base64   
    public static String GetImageStr() {
        String imgFile = "D:\\tanbing.jpg";//       
        InputStream in = null;
        byte[] data = null;
        //         
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //      Base64  
        BASE64Encoder encoder = new BASE64Encoder();
        System.out.println(encoder.encode(data));
        return encoder.encode(data);//   Base64           
    }

    //           Base64       
    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:\\tanbing2.jpg";//       
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

좋은 웹페이지 즐겨찾기