发布时间:2018-05-19作者:laosun阅读(4434)
java,Base64和图片互相转换
直接上代码(本站发过的代码都是经过博主亲自测试过的):
// _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖保佑 永无BUG // 佛曰: // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见满街漂亮妹,哪个归得程序员? import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Base64; /** * java实现Base64编码和图片互相转换 * * @author sun * @date 2018年5月18日 上午10:50:46 */ public class Demo { /** * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 * * @author sun * @date 2018年5月18日 上午10:50:37 * @param path * 图片路径 * @return */ public static String imageToBase64(String path) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 byte[] data = null; // 读取图片字节数组 try { InputStream in = new FileInputStream(path); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 对字节数组Base64编码 JDK8以上 Base64.Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(data);// 返回Base64编码过的字节数组字符串 } /** * 对字节数组字符串进行Base64解码并生成图片 * * @author sun * @date 2018年5月18日 上午10:50:22 * @param base64 * 图片Base64数据 * @param path * 图片路径 * @return */ public static boolean base64ToImage(String base64, String path) {// 对字节数组字符串进行Base64解码并生成图片 if (base64 == null) { // 图像数据为空 return false; } // JDK8以上 Base64.Decoder decoder = Base64.getDecoder(); try { // Base64解码 byte[] bytes = decoder.decode(base64); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) {// 调整异常数据 bytes[i] += 256; } } // 生成jpeg图片 OutputStream out = new FileOutputStream(path); out.write(bytes); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } public static void main(String[] args) { String encodeStr = imageToBase64("/Users/sun/Documents/1.png"); System.out.println("Base64:"+encodeStr); System.out.println(base64ToImage(encodeStr, "/Users/sun/Documents/2.png")); } }
版权属于: 技术客
原文地址: https://www.sunjs.com/article/detail/25d979888d974cd181bf877fb41db81d.html
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。