我们知道图片有很多种存储和表达形式,那么在开发中遇到图片转Base64的需求也是非常常见的,今天我们就来看看如何将图片转换成Base64字符串的。
注意:此处会用到sun.misc.BASE64Encoder工具类,这个包并不自带,建议升级到JDK8,若要下载该包请在公众号中回复20200606即可获得下载地址
NO.1 【基本工具】
public static String encodeBase64(byte[] bytes){ BASE64Encoder decoder = new BASE64Encoder(); return StringUtil.removeEnter(decoder.encode(bytes));}public static String removeEnter(String str){ String reg ="[\n-\r]"; Matcher m = Pattern.compile(reg).matcher(str); return m.replaceAll("");}
NO.2 【本地图片转换Base64】
public static String img2Base64(String imgPath) { byte[] data = null; //获取图片字节数组 try { InputStream in = new FileInputStream(imgPath); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } String result = StringUtil.encodeBase64(data); System.out.println(result); return result;}
NO.3 【网络图片转换Base64】
/** * URL资源转换为byte[] * @param url * @return * @throws IOException */public static byte[] url2byte(String url) throws IOException{ URL httpUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection(); //设置超时间为3秒 conn.setConnectTimeout(3*1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 InputStream inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStreamToBytes(inputStream); if(inputStream != null) { inputStream.close(); } return getData;}public static String imgUrl2Base64( String url ) throws IOException { byte[] bytes = url2byte(url); return StringUtil.encodeBase64(bytes);}
注:此处转换成Base64后删除了data:image/jpg;base64,前缀。
NO.4 【BASE64转换为图片】
/** * Base64转图片 * @param base64 BASE64字符串,必须为去前缀的字符串即不含"data:image/jpg;base64," * @param filePath 图片存储路径 * @return */private static String base64ToImg(String base64,String filePath){ if( StringUtils.isBlank(base64) ){ return null; } BASE64Decoder decoder = new BASE64Decoder(); try { //Base64解码 byte[] b = decoder.decodeBuffer(base64); for (int i = 0; i < b.length; i++) { if (b[i] < 0) { b[i] += 256; } } File file = new File(filePath); if(file.exists()){ file.delete(); } FileOutputStream fos = new FileOutputStream(file); fos.write(b); fos.flush(); fos.close(); return filePath; }catch(Exception e){ return null; }}
【精彩推荐】
Linux脚本启动jar包
HMAC-MD5签名算法
Java计算经纬度之间的距离
