Spring Base 64 Utils工具類使用


業務上の需要
ページ上でスクリーンショットプラグインを使って直接にbase 64の文字列を得て、直接データベースの中で検索するのはとても遅いので、base 64をファイルに変換してディスクに保存します.
例は次の通りです.base 64テキストが大きすぎるので、1枚の図を探してbase 64に変えてからbase 64を他の写真に保存します.写真は自分で探してください.
package com.ac.hdx.base.framework.utils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Base64Utils;

public class Base64Util {
	
	public static void main(String[] args) {
		String imgBase64Str = Base64Util.ImageToBase64ByLocal("C:\\Users\\Administrator\\Desktop\\         .jpg");
		
        System.out.println(imgBase64Str);
 
        boolean b = Base64Util.Base64ToImage(imgBase64Str,"C:\\Users\\Administrator\\Desktop\\test.jpg");
        System.out.println(b);
	}
	
    /**
     *        base64   
     * @param imgFile	        (  :    )
     *  (               ,     Base64    )
     * @return
     */
    public static String ImageToBase64ByLocal(String imgFile) {
 
 
        byte[] data = null;
 
        //         
        try {
            InputStream in = new FileInputStream(imgFile);
 
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
       //   Base64           
        return Base64Utils.encodeToString(data);
    }
 
 
 
 
    /**
     * base64         (          Base64       )
     * @param imgStr		base64   
     * @param imgFilePath	          (  :    )
     * @return
     */
    public static boolean Base64ToImage(String imgStr,String imgFilePath) {
 
        if (StringUtils.isEmpty(imgStr)) //       
            return false;
 
        try {
            // Base64  
            byte[] b = Base64Utils.decodeFromString(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//       
                    b[i] += 256;
                }
            }
 
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
 
            return true;
        } catch (Exception e) {
            return false;
        }
 
    }
}