简体   繁体   English

如何在Java中将SVG转换为JPEG

[英]How convert SVG to JPEG in java

I have a MulipartFile object which caries an SVG image. 我有一个MulipartFile对象,它带有SVG图像。 I want to convert that into JPEG format . 我想将其转换为JPEG格式 How can I achieve this ? 我该如何实现? I tried the following, But getting an Enclosed Exception as the system cannot find the file specified. 我尝试了以下操作,但是由于系统找不到指定的文件而导致了封闭的异常。

        JPEGTranscoder t = new JPEGTranscoder();

        File f = new File("temp.svg");
        multipartfile.transferTo(f);
        // Create a JPEG transcoder

        // Set the transcoding hints.
        t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,
                   new Float(.8));

        // Create the transcoder input.
        String svgURI = f.toURL().toString();
        TranscoderInput input = new TranscoderInput(svgURI);

        // Create the transcoder output.
        OutputStream ostream = new FileOutputStream("out.jpg");
        TranscoderOutput output = new TranscoderOutput(ostream);

        // Save the image.
        t.transcode(input, output);

        // Flush and close the stream.
        ostream.flush();
        ostream.close();

I assume you are using batik 1.8, as following steps are working with batik 1.7 but fail with 1.8. 我假设您使用的是蜡染1.8,因为以下步骤适用于蜡染1.7,但无法使用1.8。

  1. download the binary distribution version 1.7 from one of the batik download mirrors 从其中一个蜡染下载镜像中下载二进制发行版1.7
  2. extract the archive (will create directory ./batik-1.7.1/ 解压缩档案(将创建目录./batik-1.7.1/
  3. save the example SaveAsJPEG.java from batik transcoder example 保存蜡染代码转换器示例中的示例SaveAsJPEG.java
  4. compile it 编译它
    javac -cp batik-1.7.1/batik.jar SaveAsJPEG.java
  5. run it 运行
    java -cp batik.jar:. SaveAsJPEG foobar.svg

This will create an out.jpg . 这将创建一个out.jpg

Using the same steps for version 1.8 lead into 对1.8版使用相同的步骤导入

Exception in thread "main" org.apache.batik.transcoder.TranscoderException: null
Enclosed Exception:
null
     at org.apache.batik.transcoder.image.ImageTranscoder.transcode(Unknown Source)
     at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(Unknown Source)
     at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(Unknown Source)
     at SaveAsJPEG.main(SaveAsJPEG.java:27)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM