将二进制数据转换为图像

时间:2012-10-11 20:52:43

标签: java image http binary

我遇到了问题,希望你能帮助我。问题如下。我有一个有http服务的相机,我正在使用http与相机通信。所以我发送http请求,我收到一个http响应,其中我有一个二进制jpeg数据。但我不知道如何将这些数据转换成图片。所以我的问题,我的主要问题是如何将二进制数据转换为图片。

到目前为止,这是我的代码,我无法获取图像。

URL url = new URL("http://10.10.1.154" + GETIMAGESCR());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
// while ((inputLine = in.readLine()) != null){
// inputLine = in.readLine();
File file = new File("D:\\alphas\\proba.bin");
boolean postoi = file.createNewFile();
FileWriter fstream = new FileWriter("D:\\alphas\\proba.bin");
BufferedWriter out = new BufferedWriter(fstream);
while ((inputLine = in.readLine()) != null){
out.write(in.readLine());
// out.close();
// System.out.println("File created successfully.");
System.out.println(inputLine);
}
System.out.println("File created successfully.");
out.close();
in.close()

2 个答案:

答案 0 :(得分:3)

试试这段代码:

URL url = new URL("http://10.10.1.154" + GETIMAGESCR());
InputStream is = new InputStream(url.openStream());
FileOutputStream out = new FileOutputStream("D:\\alphas\\proba.jpg");
byte[] data = new byte[1024];
int readBytes = 0;
while ((readBytes = is.read(data)) > 0) {
  out.write(data,0,readBytes);
}
out.flush();
out.close();
is.close()

答案 1 :(得分:1)

您可以使用javax.imageio.ImageIO

URL url = new URL("http://10.10.1.154" + GETIMAGESCR());
BufferedImage bi = ImageIO.read(url.openStream())