圖片轉(zhuǎn)二進制流并通過HTTP上傳到靜態(tài)文件服務(wù)器

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就行。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容