0

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

4

1 回答 1

1

我使用类似的东西从 url 下载图像:
import java.io.IOException; 导入 java.io.InputStream;导入 java.net.HttpURLConnection;导入 java.net.URL;导入 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();
于 2013-02-11T12:08:18.933 回答