[英]receive an image and display it with tcp socket? (android)
我如何接收圖像並通過帶有Android設備的tcp套接字顯示它? 我嘗試了一些但不起作用。 我正在搜索一些示例以從PC發送圖像或文件並將其保存在手機上(android,java)
我使用類似的方法從URL下載圖像:
導入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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.