【问题标题】:Read Image from Socket [duplicate]从套接字读取图像[重复]
【发布时间】:2012-01-30 14:41:34
【问题描述】:

可能重复:
Read Image File Through 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();     
}

-创建一个套接字 - 创建输出流 -请求包含图像的页面 - 将套接字读取到输入流 -写入文件

我正在尝试从套接字读取图像。 但它不起作用。

好像读过,图片打开了却看不到

问题出在哪里?

【问题讨论】:

  • 你为什么不为此使用 RTP 类?
  • 什么不起作用?有什么例外吗?堆栈跟踪是什么?你知道 Java 本身就支持 HTTP 吗?查看 URLConnection。
  • 这是今天早上的第二个“从套接字读取图像”问题。

标签: java image sockets


【解决方案1】:

您可以直接使用 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 
           (i.e. 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 */
            }
        }
    }

}

【讨论】:

    【解决方案2】:

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

    这个问题我今天已经回答过了,看:Read Image File Through Java Socket

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-13
      • 2016-06-28
      • 2021-12-19
      • 2011-10-29
      • 2015-09-27
      • 2019-04-02
      • 2013-10-12
      相关资源
      最近更新 更多