接收图像并用tcp socket显示它? (机器人)

时间:2013-02-11 11:22:24

标签: java android sockets mobile tcp

我如何接收图像并使用带有Android设备的tcp套接字显示它?我尝试了一些但不起作用。我正在寻找一些例子来从pc发送图像或文件并将其保存在手机上(android,java)

1 个答案:

答案 0 :(得分:1)

我使用类似的东西从网址下载图片:
    import java.io.IOException;     import java.io.InputStream;     import java.net.HttpURLConnection;     import java.net.URL;     import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class AsyncDownloadImage extends AsyncTask<ImageView, Void, Bitmap> {

    private static final String TAG = "AsyncDownloadImage";
    ImageView imageView = null;

    @Override
    protected Bitmap doInBackground(ImageView... imageViews) {
        this.imageView = imageViews[0];
        return DownloadImage((String) imageView.getTag());
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if (result != null)
            imageView.setImageBitmap(result);
    }

    private InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

    private Bitmap DownloadImage(String URL) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            if (in != null)
                in.close();
        } catch (IOException e1) {
            Log.e(TAG, "Error in downloading image");
            e1.printStackTrace();
        }
        return bitmap;
    }
}

我使用它的方法是在imageview的标记中设置我想要下载的图像的url并将其作为参数传递给ImageView。例如。

ImageView iv.setTag("http://www.example.com/image.png");
new AsyncDownloadImage().execute(iv);

如果您想使用套接字下载它,可以打开套接字连接,如:

Socket socket = new Socket(ip, port);
InputStream inputStream = socket.getInputStream();