从套接字读取图像

可能重复:
通过Java Socket读取映像文件

void readImage() throws IOException { socket = new Socket("upload.wikimedia.org", 80); DataOutputStream bw = new DataOutputStream(new DataOutputStream(socket.getOutputStream())); bw.writeBytes("GET /wikipedia/commons/8/80/Knut_IMG_8095.jpg HTTP/1.1\n"); bw.writeBytes("Host: wlab.cs.bilkent.edu.tr:80\n\n"); DataInputStream in = new DataInputStream(socket.getInputStream()); File file = new File("imgg.jpg"); file.createNewFile(); DataOutputStream dos = new DataOutputStream(new FileOutputStream(file)); int count; byte[] buffer = new byte[8192]; while ((count = in.read(buffer)) > 0) { dos.write(buffer, 0, count); dos.flush(); } dos.close(); System.out.println("image transfer done"); socket.close(); } 

– 创建套接字 – 创建输出流 – 请求包含图像的页面-Read套接字到输入流 – 写入文件

我试图从套接字读取图像。 但它没有用。

它似乎阅读,图像打开但无法看到

哪里有问题?

您需要跳过HTTP标头才能获得正确的图像。

我今天已经回答了这个问题,请看: 通过Java Socket读取图像文件

第二个问题,你试图从没有引用者和维基百科的wikipedia接收图像限制这样做(你每次都接收拒绝访问)。 尝试使用其他图片url(例如谷歌图片)。

您可以直接使用URL对象来获取HTTP内容。 URL对象返回的输入流将仅包含URL中的内容。 下面的示例方法采用URL,获取其内容并将内容写入给定文件。

 public static void createImageFile(URL url, File file) throws IOException{ FileOutputStream fos = null; InputStream is = null; byte[] b = new byte[1024]; // 1 kB read blocks. URLConnection conn; try{ conn = url.openConnection(); /* Set some connection options here before opening the stream (ie connect and read timeouts) */ is = conn.getInputStream(); fos = new FileOutputStream(file); int i = 0; do{ i = is.read(b); if(i != -1) fos.write(b, 0, i); }while(i != -1) }finally{ /* Don't forget to clean up. */ if(is != null){ try{ is.close(); }catch(Exception e){ /* Don't care */ } } if(fos != null){ try{ fos.close(); }catch(Exception e){ /* Don't care */ } } } }