在Android中,我们可以通过使用URLConnection或者OkHttp等网络库获取图片。
使用URLConnection获取图片的代码如下:
URL url = new URL("http://www.example.com/image.jpg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// 在UI线程中更新UI
runOnUiThread(new Runnable() {
@Override
public void run() {
// 在ImageView中显示图片
imageView.setImageBitmap(bitmap);
}
});
}
使用OkHttp获取图片的代码如下:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.example.com/image.jpg")
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
InputStream inputStream = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// 在UI线程中更新UI
runOnUiThread(new Runnable() {
@Override
public void run() {
// 在ImageView中显示图片
imageView.setImageBitmap(bitmap);
}
});
}
需要注意的是,上述代码都需要在子线程中执行,不能在UI线程中执行,否则会导致UI卡顿甚至ANR。可以使用AsyncTask或者使用线程池等方式在子线程中执行。
在Android中,可以使用以下步骤从网络获取图片:
- 创建一个
URL
对象,将图片的URL作为参数传递给它。
URL url = new URL("http://www.example.com/image.jpg");
- 打开
HttpURLConnection
对象,并传递该URL
对象作为参数。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- 设置连接属性,例如请求方式、连接超时时间等。
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
- 然后执行连接操作,并获取输入流。
connection.connect();
InputStream inputStream = connection.getInputStream();
- 将输入流转换成
Bitmap
对象。
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
- 最后关闭输入流和连接。
inputStream.close();
connection.disconnect();
完整代码示例:
public class NetworkImageActivity extends AppCompatActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_image);
imageView = findViewById(R.id.imageView);
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://www.example.com/image.jpg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.connect();
InputStream inputStream = connection.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
connection.disconnect();
runOnUiThread(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/154741.html