How send image from java applet to javascript?

为君一笑 提交于 2019-12-23 02:40:37

问题


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


回答1:


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 ;)




回答2:


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+'"/>');


来源:https://stackoverflow.com/questions/13725734/how-send-image-from-java-applet-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!