关于图片与base64相互转换的工具类

最近在编写平台对接软件,需要从Oracle中取出blob类型图片数据转换为base64字符串写入到xml中,这里记录一下用到的转换方法

// 将一张本地图片转化成Base64字符串
public  static String GetImageStrFromPath(String imgPath) {
    InputStream in = null;
    byte[] data = null;
    // 读取图片字节数组
    try {
        in = new FileInputStream(imgPath);
        data = new byte[in.available()];
        in.read(data);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    // 返回Base64编码过的字节数组字符串
    return encoder.encode(data);
}

// 将一张网络图片转化成Base64字符串
public  String GetImageStrFromUrl(String imgURL) {
    byte[] data = null;
    try {
        // 创建URL
        URL url = new URL(imgURL);
        // 创建链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        InputStream inStream = conn.getInputStream();
        data = new byte[inStream.available()];
        inStream.read(data);
        inStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    // 返回Base64编码过的字节数组字符串
    return encoder.encode(data);
}

// 将blob类型图片转换为Base64字符串
public static String blobToBase64(Blob blob) {
    String result = "";
    if (null != blob) {
        try {
            InputStream msgContent = blob.getBinaryStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[100];
            int n = 0;
            while (-1 != (n = msgContent.read(buffer))) {
                output.write(buffer, 0, n);
            }
            result = new BASE64Encoder().encode(output.toByteArray());
            output.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    } else {
        return null;
    }
}

// 将base64字符串转换成图片
public static boolean GenerateImage(String imgStr) {
    if (imgStr == null) // 图像数据为空
        return false;
    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;
    }
}

猜你喜欢

转载自blog.51cto.com/14221100/2396127