/** * base64字符串转化成图片 * * @param base64 * @return */ public static File base64ToFile(String base64) throws Exception { if (base64.contains("data:image")) { base64 = base64.substring(base64.indexOf(",") + 1); } base64 = base64.toString().replace("\r\n", ""); //创建文件目录 String prefix = ".jpeg"; File file = File.createTempFile(UUID.randomUUID().toString(), prefix); BufferedOutputStream bos = null; FileOutputStream fos = null; try { BASE64Decoder decoder = new BASE64Decoder(); byte[] bytes = decoder.decodeBuffer(base64); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bytes); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } return file; }
通过读取base64格式图片 并获取其width及height的方式,来判断判断当前文件是否图片
public static boolean determineIfThePictureIsValidLt(String Base64Photo) throws IOException { if (StringUtils.isNotEmpty(Base64Photo)) { String data = Base64Photo.split("base64,")[0]; String base64Image = Base64Photo.replaceFirst(data, ""); if (StringUtils.isNotEmpty(base64Image)) { byte[] decoder = new BASE64Decoder().decodeBuffer(base64Image); InputStream is = new ByteArrayInputStream(decoder); BufferedImage read = ImageIO.read(is); if (read == null || read.getWidth(null) <= 0 || read.getHeight(null) <= 0) { return false; } return true; } } return false; }
/** * 通过读取文件并获取其width及height的方式,来判断判断当前文件是否图片,这是一种非常简单的方式。 * * @param imageFile * @return */ public static boolean isImage(File imageFile) { if (!imageFile.exists()) { return false; } Image img = null; try { img = ImageIO.read(imageFile); if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) { return false; } return true; } catch (Exception e) { return false; } finally { img = null; } }
/** * 通过读取文件并获取其width及height的方式,来判断判断当前文件是否图片,这是一种非常简单的方式。 * * @param imageFile * @return */ public static boolean isImage(File imageFile) { if (!imageFile.exists()) { return false; } Image img = null; try { img = ImageIO.read(imageFile); if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) { return false; } return true; } catch (Exception e) { return false; } finally { img = null; } }
// 1.需要计算文件流大小,首先把头部的data:image/png;base64,(注意有逗号)去掉。 String str = Base64Photo.substring(22); //2.找到等号,把等号也去掉 Integer equalIndex = str.indexOf("="); if (str.indexOf("=") > 0) { str = str.substring(0, equalIndex); } //3.原来的字符流大小,单位为字节 Integer strLength = str.length(); //4.计算后得到的文件流大小,单位为字节 Integer size = strLength - (strLength / 8) * 2; Path write = Files.write(Paths.get(Base64Photo), Base64.getDecoder().decode(Base64Photo), StandardOpenOption.CREATE); Image img = null; try { img = ImageIO.read((ImageInputStream) write); if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) { return false; } return true; } catch (Exception e) { return false; }