How to render a internal image on a swing component using html?

后端 未结 4 1298
故里飘歌
故里飘歌 2021-01-19 13:05

I have the following code:

public static void main(String[] args) {
    JFrame frm = new JFrame();
    JEditorPane pane = new JEditorPane(\"text/html\", \"&l         


        
4条回答
  •  半阙折子戏
    2021-01-19 13:13

    An other way to hook an ImageView:

    public class Base64ImageView extends ImageView {
    
    private URL url;
    
    public Base64ImageView(Element elem) {
        super(elem);
    
        populateImage();
    }
    
    private void populateImage() {
        Dictionary cache = (Dictionary) getDocument()
                .getProperty("imageCache");
        if (cache == null) {
            cache = new Hashtable();
            getDocument().putProperty("imageCache", cache);
        }
    
        URL src = getImageURL();
        cache.put(src, loadImage());
    
    }
    
    private Image loadImage() {
        String b64 = getBASE64Image();
        BufferedImage newImage = null;
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(
                    Base64.decodeBase64(b64.getBytes()));
            newImage = ImageIO.read(bais);
        } catch (Throwable ex) {
        }
        return newImage;
    }
    
    private String getBASE64Image() {
        String src = (String) getElement().getAttributes()
                .getAttribute(HTML.Attribute.SRC);
        if (!isBase64Encoded(src)) {
            return null;
        }
        return src.substring(src.indexOf("base64,") + 7, src.length() - 1);
    }
    
    @Override
    public URL getImageURL() {
        String src = (String) getElement().getAttributes()
                .getAttribute(HTML.Attribute.SRC);
        if (isBase64Encoded(src)) {
    
            this.url = Base64ImageView.class.getProtectionDomain()
                    .getCodeSource().getLocation();
    
            return this.url;
        }
        return super.getImageURL();
    }
    
    private boolean isBase64Encoded(String src) {
        return src != null && src.contains("base64,");
    }
    
    }
    

提交回复
热议问题