1 圖片轉(zhuǎn)化成base64字符串
//圖片轉(zhuǎn)化成base64字符串
public static String getImageBinary(String imgFile){
BASE64Encoder encoder = new sun.misc.BASE64Encoder();
File f = new File(imgFile);
BufferedImage bi;
try {
bi = ImageIO.read(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos);
byte[] bytes = baos.toByteArray();
return encoder.encodeBuffer(bytes).trim();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
注意:在圖片轉(zhuǎn)成base64String中可能會包含\r\n,要將其去掉
String imageBinary = base64String.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
2 base64字符串轉(zhuǎn)化成圖片
//base64字符串轉(zhuǎn)化成圖片
public static boolean GenerateImage(String imgStr, String imgFilePath, String imgFileName) {
//對字節(jié)數(shù)組字符串進行Base64解碼并生成圖片
//圖像數(shù)據(jù)為空
if (imgStr == null) {
return false;
}
if(imgFilePath == null || imgFileName == null) { // 存儲路徑為空
return false;
}
File filePath = new File(imgFilePath);
if(!filePath.exists()) {
filePath.mkdirs();
}
imgFilePath = imgFilePath + imgFileName;
BASE64Decoder decoder = new BASE64Decoder();
try {
//Base64解碼
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i) {
if(b[i]<0) {//調(diào)整異常數(shù)據(jù)
b[i]+=256;
}
}
//生成jpeg圖片
//String imgFilePath = "d://222.jpg";//新生成的圖片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
imgFileName后面記得加.jpg
3 post方法采用的okhttp3
/**
* POST TO A SERVER
* @param url
* @param data
* @return
* @throws IOException
*/
public static String postRequest(String url,String data,MediaType type)throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(type, data);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
if(response.isSuccessful()){
ResponseBody responseBody = response.body();
if (responseBody != null) {
// 返回的是string 類型
String str = responseBody.string();
logger.debug("getPostRequest response =>" + str);
return str;
}
}
return null;
}
type設(shè)置為MediaType.parse("application/json; charset=utf-8")
data是我封裝的json字符串,把base64String鍵值進去。接口端直接解析data就行。