【发布时间】:2014-02-10 10:47:10
【问题描述】:
我有一个放置了图像视图的小程序。我在 Applet 中有一个“连接”按钮。单击此按钮,正在连接 java 套接字程序。这工作正常。每当 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);
}
【问题讨论】:
-
我试过这个,但它不起作用,在运行时尝试创建 RGB 图像时,会出现“数据数组太小(应该 > 29999”)的错误。
-
你上传的是图片文件的字节数,还是压缩包的字节数?
-
图片文件的字节数。我只需要将这个字节数据转换成图像并在 g.drawImage(sharedImage, 100, 100, this); 中更新即可;