小程序:将图像字节数据转换为图像

时间:2014-02-10 10:47:11

标签: java applet

我有一个放置了图像视图的Applet。我在Applet中有一个“连接”按钮。单击此按钮,将连接Java套接字程序。这工作正常。只要Applet与它连接,套接字就会返回一个图像数据(字节格式)。图像数据正确地进入Applet而没有任何问题。但是,我不知道,如何转换此图像数据并将其作为图像放置在该图像视图中?

请帮助解决这个问题?

我的Apple代码如下:

public void actionPerformed(ActionEvent e)
{
    if(e.getSource() == connectBtn)
        //Create a socket
    try
    {
        localSocket = new Socket(this.getCodeBase().getHost(), 8080);
        input = localSocket.getInputStream();
        outStream = new PrintStream(localSocket.getOutputStream());

        byte[] data = new byte[0];
        byte[] buffer = new byte[1024];
        int bytesRead;

        try {
            do {

                bytesRead = input.read(buffer);

                byte[] newData = new byte[data.length + bytesRead];

                System.arraycopy(data, 0, newData, 0, data.length);

                System.arraycopy(buffer, 0, newData, data.length, bytesRead);
                // set data equal to newData in prep for next block of data
                data = newData;
            } while (input.available() != 0);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("data length: " + data.length);

        // STEP 1: Convert this "data" to an Image
        // STEP 2: Need to update this image with the existing image. Should I have to repaint?


    }
    catch(UnknownHostException unc)
    {
        System.out.println("Connection why not connected");
    }
    catch(IOException ioe)
    {
        System.out.println(ioe.getMessage());
    }
}
public void paint (final Graphics g)
{
    super.paint(g);
    g.drawString(str, 50, 50);
    sharedImage = getImage(getDocumentBase(), "/Users/ScreenShare/testImage.png");
    g.drawImage(sharedImage, 100, 100, this);
}

2 个答案:

答案 0 :(得分:0)

以下是如何将图像加载到applet的简单示例:
http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html

如果你只想要图像本身就是另一个例子:
http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/

答案 1 :(得分:0)

您的字节数组是 b

image = new ImageIcon(b).getImage();

然后在您的代码中设置它:

 g.drawImage(image, 100, 100, this);