接口上传base64编码图片

1 package com.*.util; 2 3 import java.io.FileInputStream; 4 5 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.OutputStream; 10 import java.util.Date; 11 12 import Decoder.BASE64Decoder; 13 import Decoder.BASE64Encoder; 14 15 public class Base64ImgUtils { 16public static void main(String[] args) { 17String strImg = GetImageStr(); 18System.out.println(strImg); 19GenerateImage(strImg); 20} 21 22/** 23* 图片转化成base64字符串 24* GetImageStr 25* 2016年8月31日下午3:37:40 26* @param 27* @return 28*/ 29public static String GetImageStr() {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 30String imgFile = "D:/486e407765c21edd9cbffca69717efb1.jpg"; // 待处理的图片 31InputStream in = null; 32byte[] data = https://www.it610.com/article/null; 33// 读取图片字节数组 34try { 35in = new FileInputStream(imgFile); 36data = new byte[in.available()]; 37in.read(data); 38in.close(); 39} catch (IOException e) { 40e.printStackTrace(); 41} 42// 对字节数组Base64编码 43BASE64Encoder encoder = new BASE64Encoder(); 44String imghead="data:image/jpg; base64,"; //头 45return imghead+encoder.encode(data); // 返回Base64编码过的字节数组字符串 46} 47 48/** 49* base64字符串转化成图片 50* GenerateImage 51* 2016年8月31日下午3:33:12 52* @param 53* @return 54*/ 55public static String GenerateImage(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片 56if (imgStr == null){ // 图像数据为空 57return ""; 58} 59String classPath = new Base64ImgUtils().getClass().getResource("").getPath(); 60String path = classPath.substring(0, classPath.indexOf("WEB-INF")); 61System.out.println(path); 62BASE64Decoder decoder = new BASE64Decoder(); 63try { 64String imghead=imgStr.substring(0,imgStr.indexOf("; ")).replace("data:image/", "."); //获取图片扩展名 65imgStr=imgStr.substring(imgStr.indexOf(",")+1); //图片内容 66 67// Base64解码 68byte[] b = decoder.decodeBuffer(imgStr); 69for (int i = 0; i < b.length; ++i) { 70if (b[i] < 0) {// 调整异常数据 71b[i] += 256; 72} 73} 74// 生成jpeg图片 75String filename="upload/"+new Date().getTime()+imghead; //名称 76String imgFilePath =path+"/"+filename; // 新生成的图片 77OutputStream out = new FileOutputStream(imgFilePath); 78out.write(b); 79out.flush(); 80out.close(); 81return filename; 82} catch (Exception e) { 83return ""; 84} 85} 86 87 88 }

【接口上传base64编码图片】
转载于:https://www.cnblogs.com/-lpf/p/5827114.html

    推荐阅读