从网址加载图片

San*_*dey 147 android

我有一个图片网址.我想在ImageView中显示此URL中的图像,但我无法做到这一点.

怎么能实现这一目标?

Kyl*_*egg 302

如果您基于按钮单击加载图像,则上面接受的答案很好,但是如果您在新活动中执行此操作,则会将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);
  }
}
Run Code Online (Sandbox Code Playgroud)

并使用以下命令从onCreate()方法调用:

new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
        .execute(MY_URL_STRING);
Run Code Online (Sandbox Code Playgroud)

别忘了在清单文件中添加以下权限

<uses-permission android:name="android.permission.INTERNET"/>
Run Code Online (Sandbox Code Playgroud)

对我来说很棒.:)

  • 是的,ASYNC至关重要. (5认同)
  • 我喜欢这个解决方案,你应该只清理 onPostExecute 的代码,因为它的主体已经出来了。 (2认同)

raj*_*ath 228

URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
Run Code Online (Sandbox Code Playgroud)

  • 你真的不应该使用它,因为它阻止了UI线程.该库将为您处理线程和下载:https://github.com/koush/UrlImageViewHelper (59认同)
  • 如果你在一个单独的线程上运行该块减去setImageBitmap就行了 (16认同)
  • https://github.com/nostra13/Android-Universal-Image-Loader是我的最爱 (4认同)
  • @koush - 如果包含在`AsyncTask`中,这段代码就可以了. (4认同)
  • 你应该在一个单独的线程中进行任何networl操作,当加载了位图时,你可以使用ImageView.post()或Handler.post() (2认同)

vij*_*icv 29

尽力而为picassso,并在一个声明中完成

Picasso.with(context)
                .load(ImageURL)
                .resize(width,height).into(imageView);
Run Code Online (Sandbox Code Playgroud)

教程:https: //youtu.be/DxRqxsEPc2s

  • 毕加索,格莱德也是我的最爱.Glide的声明与Picasso完全相似,缓存大小有很大改进. (3认同)

小智 9

试试这个添加picasso lib jar文件

Picasso.with(context)
                .load(ImageURL)
                .resize(width,height).noFade().into(imageView);
Run Code Online (Sandbox Code Playgroud)


小智 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();
        }


    }


}
Run Code Online (Sandbox Code Playgroud)

在你的活动中拍摄imageview并设置资源imageDownload(url,yourImageview);


San*_*inh 7

有两种方式:

1) 使用 Glide 库这是从 url 加载图像的最佳方式,因为当您尝试第二次显示相同的 url 时,它将从 catch 显示,从而提高应用程序性能

Glide.with(context).load("YourUrl").into(imageView);
Run Code Online (Sandbox Code Playgroud)

依赖: implementation 'com.github.bumptech.glide:glide:4.10.0'


2)使用流。在这里你想从 url 图像创建位图

URL url = new URL("YourUrl");
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);
Run Code Online (Sandbox Code Playgroud)


kou*_*ush 5

UrlImageViewHelper将使用在URL处找到的图像填充ImageView.UrlImageViewHelper将自动下载,保存和缓存BitmapDrawables的所有图像URL.重复的网址不会被加载到内存中两次.位图内存通过使用弱引用哈希表进行管理,因此只要您不再使用该图像,就会自动对其进行垃圾回收.

UrlImageViewHelper.setUrlDrawable(imageView,"http://example.com/image.png");

https://github.com/koush/UrlImageViewHelper


Ser*_*kov 5

基于这个答案,我编写了自己的加载程序。

具有加载效果和出现效果:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

添加权限

<uses-permission android:name="android.permission.INTERNET"/>
Run Code Online (Sandbox Code Playgroud)

并执行:

 new DownloadImageTask(context, imageViewToLoad, urlToImage).execute();
Run Code Online (Sandbox Code Playgroud)


小智 5

在清单中添加互联网权限

<uses-permission android:name="android.permission.INTERNET" />
Run Code Online (Sandbox Code Playgroud)

而不是创建如下方法,

 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在将其添加到您的 onCreate 方法中,

 ImageView img_add = (ImageView) findViewById(R.id.img_add);


img_add.setImageBitmap(getBitmapFromURL("http://www.deepanelango.me/wpcontent/uploads/2017/06/noyyal1.jpg"));
Run Code Online (Sandbox Code Playgroud)

这对我有用。