想从互联网上获取照片,所以我使用 setImageURI,但似乎无法完成,但如果我使用 setImageResource(R.drawable.)
最重要的事情
setImageResource 是同步的,因此它会正确执行,但来自 URL 的 setImageURI 是异步操作,它必须在与 UI 线程不同的线程中执行
关注 Snippet 将对您有所帮助。
new Thread() {
public void run() {
try {
url = new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
image = BitmapFactory.decodeStream(url.openStream());
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
i.setImageBitmap(image);
}
});
}
}.start();
如果这也不起作用,那么您还有其他三个选择
选项1
URL myUrl = new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg");
InputStream inputStream = (InputStream)myUrl.getContent();
Drawable drawable = Drawable.createFromStream(inputStream, null);
i.setImageDrawable(drawable);
选项2
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg").getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
选项3
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
i.setImageBitmap(loadBitmap("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg"));