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 に答える