【Java】

您所在的位置:网站首页 皮手套的图片 【Java】

【Java】

2023-06-09 13:23| 来源: 网络整理| 查看: 265

一、如何使用base64格式获取图片长、宽度。支持图片类型有:svg、png、jpg、jpeg等。

1.java实例代码如下:(代码中存在封装后方法,复制过去会出现错误提示,属于正常现象、需要自己微改!) 

//获取SVG长宽 public static JSONObject fn_SVG_WIDTH_HEIGHT(String svgURI) throws Exception { File file = new File(svgURI); String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser); Document doc = f.createDocument(file.toURI().toString()); Element element = doc.getDocumentElement(); String width = element.getAttribute("width"); String height = element.getAttribute("height"); JSONObject svgJson=new JSONObject(); svgJson.put("width",width); svgJson.put("height",height); return svgJson; } //获取ICON长宽 public JSONObject fn_get_file_width_height(String v_BAES64,FileInfo info)throws Exception{ JSONObject jsonObject=new JSONObject(); jsonObject.put("width",""); jsonObject.put("height",""); // 图片对象 String fileBase=""; if(v_BAES64.equals("")==false){ if(v_BAES64.contains("png")){ fileBase=v_BAES64.replaceAll("data:image/png;base64,", ""); }else if(v_BAES64.contains("jpg")){ fileBase=v_BAES64.replaceAll("data:image/jpg;base64,", ""); }else if(v_BAES64.contains("svg")){ String len="data:image/svg+xml;base64,"; fileBase=v_BAES64.substring(len.length(),v_BAES64.length()); }else if(v_BAES64.contains("jpeg")){ fileBase=v_BAES64.replaceAll("data:image/jpeg;base64,", ""); }else if(v_BAES64.contains("gif")){ fileBase=v_BAES64.replaceAll("data:image/gif;base64,", ""); } } if(fileBase.equals("")==false){ if(info.getType().equals("image/svg+xml")==false){ byte [] decoder = new BASE64Decoder().decodeBuffer(fileBase); InputStream fileStream=new ByteArrayInputStream(decoder); BufferedImage bufferedImage = ImageIO.read(fileStream); if(bufferedImage!=null){ // 宽度 int width = bufferedImage.getWidth(); // 高度 int height = bufferedImage.getHeight(); jsonObject.put("width",width); jsonObject.put("height",height); bufferedImage = null; fileStream.close(); } }else{ try { byte [] decoder = new BASE64Decoder().decodeBuffer(fileBase); for (int i = 0; i < decoder.length; ++i) { if (decoder[i] < 0) {// 调整异常数据 decoder[i] += 256; } } File file = new File(com.imx.tool.AppConfigFileHelper.get_UploadFolder() + "\\" + tool.IDHelper.NewGUID()); // 如果要返回file文件这边return就可以了,存到临时文件中 OutputStream out = new FileOutputStream(file.getPath()); out.write(decoder); out.flush(); out.close(); JSONObject svgJson=fn_SVG_WIDTH_HEIGHT(file.getPath()); jsonObject.put("width",svgJson.getString("width")); jsonObject.put("height",svgJson.getString("height")); tool.FileHelper.DelFile(file.getPath());//删除本地文件 } catch (Exception e) { } } } return jsonObject; }

最后效果图:如下



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3