Android(安卓)图片转换为 Base64 编码
16lz
2021-01-24
将图片转换成Base64编码的字符串
/** * 将图片转换成Base64编码的字符串 */ public static String imageToBase64(String path){ if(TextUtils.isEmpty(path)){ return null; } InputStream is = null; byte[] data = null; String result = null; try{ is = new FileInputStream(path); //创建一个字符流大小的数组。 data = new byte[is.available()]; //写入数组 is.read(data); //用默认的编码格式进行编码 result = Base64.encodeToString(data,Base64.DEFAULT); }catch (Exception e){ e.printStackTrace(); }finally { if(null !=is){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }
Android端使用Base64加密解密时应使用Base64.NO_WRAP
其他几种加密解密方式的含义:
CRLF:这个参数看起来比较眼熟,它就是Win风格的换行符,意思就是使用CR LF这一对作为一行的结尾而不是Unix风格的LF
DEFAULT:这个参数是默认,使用默认的方法来加密
NO_PADDING:这个参数是略去加密字符串最后的“=”
NO_WRAP:这个参数意思是略去所有的换行符(设置后CRLF就没用了)
URL_SAFE:这个参数意思是加密时不使用对URL和文件名有特殊意义的字符来作为加密字符,具体就是以-和_取代+和/
将Base64编码的字符串转换成图片
/** * 将Base64编码转换为图片 * @param base64Str * @param path * @return true */ public static boolean base64ToFile(String base64Str,String path) { byte[] data = Base64.decode(base64Str,Base64.NO_WRAP); for (int i = 0; i < data.length; i++) { if(data[i] < 0){ //调整异常数据 data[i] += 256; } } OutputStream os = null; try { os = new FileOutputStream(path); os.write(data); os.flush(); os.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; }catch (IOException e){ e.printStackTrace(); return false; } }
参考:https://blog.csdn.net/qq_35372900/article/details/69950867
更多相关文章
- Android调用系统, 任意比例裁剪图片
- Android(安卓)控件之Gallery图片集
- Android实现圆角矩形和圆形ImageView的方式
- Android(安卓)Activity 之 startActivityForResult 的使用
- Android将byte数组写入文件
- android中异步加载网络图片
- Android(安卓)-- Vibrator
- android canvas实现在图片上画图
- android4.4 Launcher主菜单界面同样采用背景图片的方式