java实现图片格式转换(svg、png、webp)

本文介绍了如何使用Java进行SVG图片格式转换,包括SVG到PNG的转换利用Batik工具包,以及PNG到JPEG的命令行和第三方库转换方法。
摘要由CSDN通过智能技术生成


一、svg文件

1.1 svg介绍

SVG 意为可缩放矢量图形(Scalable Vector Graphics), 使用 XML 格式定义图像。因此对svg文件的操作,可以看做对xml文件的解析。svg基础知识可以参考svg教程,在此不做过多赘述。

1.2 svg文件操作

1.2.1 获取svg文件源码

读取svg文件并转换为字符串类型,可得到源码

public String svgOriginFile(MultipartFile file) throws IOException {
   
        if (file != null) {
   
            InputStream fileInput = file.getInputStream();
            byte[] inputByte = new byte[fileInput.available()];
            fileInput.read(inputByte);
            String originFile = new String(inputByte, "UTF-8");
            log.info("Get svg originFile [{}]", originFile);
            fileInput.close();
            return originFile;
        }
        return null;
    }

1.2.2 获取svg文件宽高

读取svg的xml文件,获取svg文件的width、height属性

public Float svgSize(String originFile, String lengthName) throws IOException {
   
        if (originFile != null && lengthName != null) {
   
            Document doc = svgDocument(originFile);
            Element element = doc.getDocumentElement();
            String length = lengthReg(element.getAttribute(lengthName));
            if (length == "" || length == null) {
   
                int num = lengthName.equals("width") ? 2 : 3;
                String viewBox = element.getAttribute("viewBox");
                length = viewBox.split(" ")[num];
            }
            log.info("Svg {} size is {}", lengthName, length);
            return Float.parseFloat(length);
        }
        return null;
    }


public Document svgDocument(String originFile) throws IOException {
   
        byte[] bytes = originFile.getBytes("utf-8");
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        String parser = XMLResourceDescriptor.getXMLParserClassName();
        SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
        Document doc = f.createDocument(null, inputStream);
        return doc;
    }

public String lengthReg(String str) {
   
        //用正则表达式
        String reg = "[^0-9]";
        //Pattern类的作用在于编译正则表达式后创建一个匹配模式.
        Pattern p = Pattern.compile(reg);
        //Matcher类使用Pattern实例提供的模式信息对正则表达式进行匹配
        Matcher m = p.matcher(str);
        return m.replaceAll(
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值