实际开发中涉及图片上传并且量比较大的时候一般处理方式有三种
1、直接保存到项目中 最老土直接方法,也是最不适用的方法,量大对后期部署很不方便
2、直接保存到指定路径的服务器上、需要时候在获取,这种方式很方便
3、直接保存到数据库中,需要时候解码在生成图片 下面介绍第三种方式
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
public static String GetImageStr(File file) { byte[] data = null; // 读取图片字节数组 try { InputStream in = new FileInputStream(file); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);// 返回Base64编码过的字节数组字符串 }
// 对字节数组字符串进行Base64解码并生成图片
public static boolean GenerateImage(String imgStr, String imgFilePath) { if (imgStr == null) // 图像数据为空 return false; System.out.println("照片:"+imgStr); BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解码 byte[] bytes = decoder.decodeBuffer(imgStr); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) {// 调整异常数据 bytes[i] += 256; } } // 生成jpeg图片 OutputStream out = new FileOutputStream(imgFilePath); out.write(bytes); out.flush(); out.close(); return true; } catch (Exception e) { return false; } }
转载于:https://www.cnblogs.com/weiyi1314/p/10413778.html
相关资源:图片文件与Base64编码字节数组字符串互转