软件工程师成长日记

图片转二进制流并通过HTTP上传到静态文件服务器

2019-08-08  本文已影响1人  麦克劳林
1 图片转化成base64字符串
//图片转化成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 "";
}

注意:在图片转成base64String中可能会包含\r\n,要将其去掉

 String imageBinary = base64String.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
2 base64字符串转化成图片
//base64字符串转化成图片
public static boolean GenerateImage(String imgStr, String imgFilePath, String imgFileName) {
    //对字节数组字符串进行Base64解码并生成图片
    //图像数据为空        
    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) {//调整异常数据
                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设置为MediaType.parse("application/json; charset=utf-8")

data是我封装的json字符串,把base64String键值进去。接口端直接解析data就行。

上一篇下一篇

猜你喜欢

热点阅读