加入收藏 | 设为首页 | 会员中心 | 我要投稿 南平站长网 (https://www.0599zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2021-03-14 21:45:53 所属栏目:百科 来源:网络整理
导读:最近在编写平台对接软件,需要从Oracle中取出blob类型图片数据转换为base64字符串写入到xml中,这里记录一下用到的转换方法 // 将一张本地图片转化成Base64字符串 public static String GetImageStrFromPath(String imgPath) { InputStream in = null; byt

最近在编写平台对接软件,需要从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,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; } }

(编辑:南平站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读