How send image from java applet to javascript?

2019-06-06 15:22发布

I have code in JAVA

import java.applet.Applet; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.TextArea; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO;

public class JavaScriptToJava extends Applet{

    TextArea textBox;
    Image img;
    MediaTracker tr;
    public void init(){
        setLayout(new FlowLayout());
        textBox = new TextArea(5,40);
        add(textBox);
    }

    public void appendText(String text){
        textBox.append(text);

           Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                try {
                        //Get data from clipboard and assign it to an image.
                        //clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
                        BufferedImage image = (BufferedImage)clipboard.getData(DataFlavor.imageFlavor);


                }
                //getData throws this.
                catch(UnsupportedFlavorException ufe) {
                        ufe.printStackTrace();
                }

                catch(IOException ioe) {
                        ioe.printStackTrace();
                }
    }       



}

I need get this image in javascript. How do this?

My main task is to copy the images from the clipboard and transfer it to the html page calling js

2条回答
在下西门庆
2楼-- · 2019-06-06 15:57

depends on what you want to with the image in the javascript. if you just want to show it on screen you might want to have a look at Embedding Base64 Images

Otherwise if you want to crop or resize it with javascript and then send it to a server things will be getting more tricky ;)

查看更多
做个烂人
3楼-- · 2019-06-06 16:08

Create a Java method to get a pixel from your BufferedImage:

public int getPixel(int xLoc, int yLoc) {
    int argb = myImage.getRGB(xLoc, yLoc);
    int rgba = // ... convert to rgba;
    return rgba;
}

I think it should also be possible to call the applet just once and pass an array to your JavaScript code.

In JavaScript, create a Canvas element, then call applet for each pixel and set in Canvas. (More info about how to call applet from JavaScript.) (Tutorial on HMTL Canvas pixel manipulation.)

A step further:

var myCanvas = document.getElementById("myCanvas");
var myImg    = myCanvas.toDataURL("image/png");
document.write('<img src="'+myImg+'"/>');
查看更多
登录 后发表回答