摇摆& Batik:从SVG文件创建一个ImageIcon? [英] Swing & Batik: Create an ImageIcon from an SVG file?

查看:331
本文介绍了摇摆& Batik:从SVG文件创建一个ImageIcon?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单地说,我正在寻找一种使用batik库从SVG文件制作ImageIcon的方法。我不想首先将SVG光栅转换为磁盘,我只是希望能够从jar文件中提取svg并将其作为UI元素。

Simply put, I'm looking for a way to make an ImageIcon from an SVG file using the batik library. I don't want to have to raster the SVG to disk first, I just want to be able to pull an svg out of the jar file and have it land as a UI element.

我觉得这应该相当容易,但蜡染javadocs并没有告诉我我需要知道什么。

I feel like this should be reasonably easy, but the batik javadocs aren't telling me what I need to know.

(为什么蜡染?好吧,我们已经在使用它了,所以我们不必再运行另一个合法的库。)

(Why batik? Well, we're already using it, so we don't have to run another library past legal.)

推荐答案

这真的很容易,只是不太直观。

It's really quite easy, just not very intuitive.

你需要扩展 ImageTranscoder 。在 createImage 方法中,您分配 BufferedImage ,将其缓存为成员变量,然后将其返回。 writeImage 方法为空。你需要添加一个getter来检索 BufferedImage

You need to extend ImageTranscoder. In the createImage method you allocate a BufferedImage, cache it as a member variable, and return it. The writeImage method is empty. And you'll need to add a getter to retrieve the BufferedImage.

它看起来像这样:

    class MyTranscoder extends ImageTranscoder {
        private BufferedImage image = null;
        public BufferedImage createImage(int w, int h) {
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            return image;
        }
        public void writeImage(BufferedImage img, TranscoderOutput out) {
        }
        public BufferedImage getImage() {
            return image;
        }
    }

现在,要创建图像,您需要创建一个实例您的代码转换器并通过设置 TranscodingHints 将其传递给所需的宽度和高度。最后,您从TranscoderInput转码为空目标。然后调用代码转换器上的getter来获取图像。

Now, to create an image you create an instance of your transcoder and pass it the desired width and height by setting TranscodingHints. Finally you transcode from a TranscoderInput to a null target. Then call the getter on your transcoder to obtain the image.

调用如下所示:

    MyTranscoder transcoder = new MyTransCoder();
    TranscodingHints hints = new TranscodingHints();
    hints.put(ImageTranscoder.KEY_WIDTH, width);
    hints.put(ImageTranscoder.KEY_HEIGHT, height);
    transcoder.setTranscodingHints(hints);
    transcoder.transcode(new TranscoderInput(url), null);
    BufferedImage image = transcoder.getImage();

简单,对吗? (是的,没错。只花了我两个星期的时间来解决这个问题。叹气。)

Simple, right? (Yeah, right. Only took me 2 weeks to figure that out. Sigh.)

这篇关于摇摆& Batik:从SVG文件创建一个ImageIcon?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆