1. 本地图片转换成base64
/*** 本地图片转换成base64字符串** @param imgFile 图片本地路径* @return base64字符串* @author szs* @date -07-16*/public static String getBase64FromLocal(String imgFile) {InputStream in;byte[] data = null;// 读取图片字节数组try {in = new FileInputStream(imgFile);data = new byte[in.available()];in.read(data);in.close();} catch (IOException e) {e.printStackTrace();}return Base64.encodeBase64String(data);}
2. 网络图片转换成base64
/**** 将图片转换为Base64<br>* 将base64编码字符串解码成img图片** @param imgFile 文件地址* @return base64字符串* @author szs* @date -05-05*/public static String getBase64FromHttp(String imgFile) {if (!SomeUtil.isNoEmpty(imgFile)) {return null;}ByteArrayOutputStream data = new ByteArrayOutputStream();try {// 创建URLURL url = new URL(imgFile);byte[] by = new byte[1024];// 创建链接HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5000);InputStream is = conn.getInputStream();// 将内容放到内存中int len = -1;while ((len = is.read(by)) != -1) {data.write(by, 0, len);}is.close();} catch (IOException e) {e.printStackTrace();}// 对字节数组Base64编码return Base64.encodeBase64String(data.toByteArray());}
3.字符流转base64
/*** 字符流转bae64** @param in InputStream* @return base64字符串* @author szs* @date -05-05*/public static String getBase64FromInputStream(InputStream in) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理byte[] data = null;// 读取图片字节数组try {ByteArrayOutputStream swapStream = new ByteArrayOutputStream();byte[] buff = new byte[100];int rc = 0;while ((rc = in.read(buff, 0, 100)) > 0) {swapStream.write(buff, 0, rc);}data = swapStream.toByteArray();} catch (IOException e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}return new String(Objects.requireNonNull(Base64.encodeBase64(data)));}
4.类对象转Map
/*** 类对象转Map** @param obj Object* @return Map* @author szs* @date -05-02*/public static Map<String, Object> convertObjectToMap(Object obj) {Map<String, Object> map = new HashMap<>();try {Method[] methods = obj.getClass().getMethods();for (Method m : methods) {if (m.getName().startsWith("get") && !m.getName().startsWith("getClass")) {Object value = m.invoke(obj);map.put(m.getName().substring(3), value);}}} catch (InvocationTargetException | IllegalAccessException e) {e.printStackTrace();}return map;}
5.类对象转键值对字符串
/*** 类对象转键值对字符串** @param obj Object* @return 键值对字符串* @author szs* @date -05-02*/public static String convertObjectToMapStr(Object obj) {StringBuilder sb = new StringBuilder();// 类对象转MapMap<String, Object> map = convertObjectToMap(obj);for (Map.Entry<String, Object> entry : map.entrySet()) {sb.append("&");sb.append(entry.getKey());sb.append("=");sb.append(entry.getValue());}return sb.toString();}