当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Applet: Convert image bytes data to an Image

问题描述:

I have an Applet which has an image view placed. I have a 'Connect' button in the Applet. Clicking on this button, is connecting with a java socket program. This is working fine. The socket returns an image data (Bytes format), whenever Applet is connected with it. The image data is coming to the Applet properly without any issues. But, I do not know, how to convert this image data and place as an image in that image view?

Can please help to solve this?

My Apple code is below:

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

}

网友答案:

Here is a trivial example how to load an image to an applet:
http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html

If you want only the image itself here is another example:
http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/

网友答案:

Your array of bytes is b

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

Then set it in your code:

 g.drawImage(image, 100, 100, this);
分享给朋友:
您可能感兴趣的文章:
随机阅读: