我有图片网址。我想在ImageView中显示此URL中的图像,但我无法做到这一点。
如何实现这一目标?
答案 0 :(得分:295)
如果您基于按钮单击加载图像,则上面接受的答案很棒,但是如果您在新活动中执行此操作,则会将UI冻结一两秒钟。环顾四周,我发现一个简单的asynctask消除了这个问题。
使用asynctask在活动结束时添加此类:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
使用:
从onCreate()方法调用new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(MY_URL_STRING);
不要忘记在清单文件中添加以下权限
<uses-permission android:name="android.permission.INTERNET"/>
非常适合我。 :)
答案 1 :(得分:222)
URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
答案 2 :(得分:26)
尝试picassso
很好并在一个陈述中完成
Picasso.with(context)
.load(ImageURL)
.resize(width,height).into(imageView);
答案 3 :(得分:9)
试试这个 添加picasso lib jar文件
Picasso.with(context)
.load(ImageURL)
.resize(width,height).noFade().into(imageView);
答案 4 :(得分:7)
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.Toast;
public class imageDownload {
Bitmap bmImg;
void downloadfile(String fileurl,ImageView img)
{
URL myfileurl =null;
try
{
myfileurl= new URL(fileurl);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
HttpURLConnection conn= (HttpURLConnection)myfileurl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
bmImg = BitmapFactory.decodeStream(is,null,options);
img.setImageBitmap(bmImg);
//dialog.dismiss();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
// Toast.makeText(PhotoRating.this, "Connection Problem. Try Again.", Toast.LENGTH_SHORT).show();
}
}
}
在你的活动中 拍摄imageview&amp;设置资源 imageDownload(URL,yourImageview);
答案 5 :(得分:5)
UrlImageViewHelper将使用在网址上找到的图片填充ImageView。 UrlImageViewHelper将自动下载,保存和缓存BitmapDrawables的所有图像URL。重复的网址不会被加载到内存中两次。位图内存通过使用弱引用哈希表进行管理,因此只要您不再使用该图像,就会自动对其进行垃圾回收。
UrlImageViewHelper.setUrlDrawable(imageView,“http://example.com/image.png”);
答案 6 :(得分:4)
以下是从URL显示图像的示例代码。
public static Void downloadfile(String fileurl, ImageView img) {
Bitmap bmImg = null;
URL myfileurl = null;
try {
myfileurl = new URL(fileurl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myfileurl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
if (length > 0) {
int[] bitmapData = new int[length];
byte[] bitmapData2 = new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
img.setImageBitmap(bmImg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
答案 7 :(得分:4)
基于this answer,我编写了自己的装载程序。
具有加载效果和显示效果:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.InputStream;
/**
* Created by Sergey Shustikov (pandarium.shustikov@gmail.com) at 2015.
*/
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
public static final int ANIMATION_DURATION = 250;
private final ImageView mDestination, mFakeForError;
private final String mUrl;
private final ProgressBar mProgressBar;
private Animation.AnimationListener mOutAnimationListener = new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
}
@Override
public void onAnimationEnd(Animation animation)
{
mProgressBar.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
};
private Animation.AnimationListener mInAnimationListener = new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
if (isBitmapSet)
mDestination.setVisibility(View.VISIBLE);
else
mFakeForError.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animation animation)
{
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
};
private boolean isBitmapSet;
public DownloadImageTask(Context context, ImageView destination, String url)
{
mDestination = destination;
mUrl = url;
ViewGroup parent = (ViewGroup) destination.getParent();
mFakeForError = new ImageView(context);
destination.setVisibility(View.GONE);
FrameLayout layout = new FrameLayout(context);
mProgressBar = new ProgressBar(context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mProgressBar.setLayoutParams(params);
FrameLayout.LayoutParams copy = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
copy.gravity = Gravity.CENTER;
copy.width = dpToPx(48);
copy.height = dpToPx(48);
mFakeForError.setLayoutParams(copy);
mFakeForError.setVisibility(View.GONE);
mFakeForError.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
layout.addView(mProgressBar);
layout.addView(mFakeForError);
mProgressBar.setIndeterminate(true);
parent.addView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
protected Bitmap doInBackground(String... urls)
{
String urlDisplay = mUrl;
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(urlDisplay).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap result)
{
AlphaAnimation in = new AlphaAnimation(0f, 1f);
AlphaAnimation out = new AlphaAnimation(1f, 0f);
in.setDuration(ANIMATION_DURATION * 2);
out.setDuration(ANIMATION_DURATION);
out.setAnimationListener(mOutAnimationListener);
in.setAnimationListener(mInAnimationListener);
in.setStartOffset(ANIMATION_DURATION);
if (result != null) {
mDestination.setImageBitmap(result);
isBitmapSet = true;
mDestination.startAnimation(in);
} else {
mFakeForError.startAnimation(in);
}
mProgressBar.startAnimation(out);
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = mDestination.getContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
}
添加权限
<uses-permission android:name="android.permission.INTERNET"/>
执行:
new DownloadImageTask(context, imageViewToLoad, urlToImage).execute();
答案 8 :(得分:3)
我试过的最佳方法,而不是使用任何库
public Bitmap getbmpfromURL(String surl){
try {
URL url = new URL(surl);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setDoInput(true);
urlcon.connect();
InputStream in = urlcon.getInputStream();
Bitmap mIcon = BitmapFactory.decodeStream(in);
return mIcon;
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
return null;
}
}
答案 9 :(得分:3)
在清单
中添加Internet权限<uses-permission android:name="android.permission.INTERNET" />
比如下创建方法,
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src", src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap", "returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception", e.getMessage());
return null;
}
}
现在在onCreate方法中添加它,
ImageView img_add = (ImageView) findViewById(R.id.img_add);
img_add.setImageBitmap(getBitmapFromURL("http://www.deepanelango.me/wpcontent/uploads/2017/06/noyyal1.jpg"));
这对我有用。
答案 10 :(得分:3)
有两种方法:
1)使用Glide库,这是从url加载图像的最佳方法,因为当您尝试第二次显示相同的url时,它将从catch中显示出来,从而提高了应用性能
Glide.with(context).load("YourUrl").into(imageView);
依赖性:implementation 'com.github.bumptech.glide:glide:4.10.0'
2)使用流。在这里,您要根据网址图片创建位图
URL url = new URL("YourUrl");
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);
答案 11 :(得分:2)
下面的代码展示了如何使用RxAndroid从url字符串设置ImageView。 首先,添加RxAndroid库2.0
dependencies {
// RxAndroid
compile 'io.reactivex.rxjava2:rxandroid:2.0.0'
compile 'io.reactivex.rxjava2:rxjava:2.0.0'
// Utilities
compile 'org.apache.commons:commons-lang3:3.5'
}
现在使用setImageFromUrl来设置图像。
public void setImageFromUrl(final ImageView imageView, final String urlString) {
Observable.just(urlString)
.filter(new Predicate<String>() {
@Override public boolean test(String url) throws Exception {
return StringUtils.isNotBlank(url);
}
})
.map(new Function<String, Drawable>() {
@Override public Drawable apply(String s) throws Exception {
URL url = null;
try {
url = new URL(s);
return Drawable.createFromStream((InputStream) url.getContent(), "profile");
} catch (final IOException ex) {
return null;
}
}
})
.filter(new Predicate<Drawable>() {
@Override public boolean test(Drawable drawable) throws Exception {
return drawable != null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Drawable>() {
@Override public void accept(Drawable drawable) throws Exception {
imageView.setImageDrawable(drawable);
}
});
}
答案 12 :(得分:1)
loadImage("http://relinjose.com/directory/filename.png");
你去吧
void loadImage(String image_location) {
URL imageURL = null;
if (image_location != null) {
try {
imageURL = new URL(image_location);
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
ivdpfirst.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else {
//set any default
}
}
答案 13 :(得分:1)
试试这个:
InputStream input = contentResolver.openInputStream(httpuri);
Bitmap b = BitmapFactory.decodeStream(input, null, options);
答案 14 :(得分:1)
public class MainActivity extends Activity {
Bitmap b;
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imageView1);
information info = new information();
info.execute("");
}
public class information extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... arg0) {
try
{
URL url = new URL("http://10.119.120.10:80/img.jpg");
InputStream is = new BufferedInputStream(url.openStream());
b = BitmapFactory.decodeStream(is);
} catch(Exception e){}
return null;
}
@Override
protected void onPostExecute(String result) {
img.setImageBitmap(b);
}
}
}
答案 15 :(得分:1)