Tải hình ảnh từ url


155

Tôi có một URL hình ảnh. Tôi muốn hiển thị hình ảnh từ URL này trong ImageView nhưng tôi không thể làm điều đó.

Làm thế nào điều này có thể đạt được?



xem những câu hỏi này và tập trung vào những câu trả lời đầu tiên, ở đây bạn có thể tìm thấy hai cách đơn giản và đầy đủ để làm điều này: phương pháp thứ nhất (đầy đủ hơn) hoặc phương pháp thứ hai (đơn giản hơn)
lory105

bạn có thể sử dụng trình tải hình ảnh Picasso và Glide và hiển thị cho chế độ xem hình ảnh
shweta c

Câu trả lời:


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

60
Bạn thực sự không nên sử dụng nó, vì nó chặn luồng UI. Thư viện này sẽ xử lý luồng và tải xuống cho bạn: github.com/koush/UrlImageViewHelper
koush

16
Không, nếu bạn chạy khối đó trên một luồng riêng biệt trừ setImageBitmap
Jonathan

nó hoạt động tôi hiển thị trong hình thu nhỏ và hình ảnh trực quan onclick tôi đã sử dụng dailog DSplaying nhưng nó sẽ mở sau 10 giây
Prasad

4
@koush - Mã này sẽ ổn nếu được bọc trong một AsyncTask.
Greg Brown

2
Bạn nên thực hiện bất kỳ thao tác networl nào trong một luồng riêng biệt, Khi bitmap đã được tải, bạn có thể sử dụng ImageView.post () hoặc Handler.post ()
Volodymyr Shalashenko

310

Câu trả lời được chấp nhận ở trên là tuyệt vời nếu bạn đang tải hình ảnh dựa trên một lần bấm nút, tuy nhiên nếu bạn đang thực hiện nó trong một hoạt động mới, nó sẽ đóng băng UI trong một hoặc hai giây. Nhìn xung quanh tôi thấy rằng một asynctask đơn giản đã loại bỏ vấn đề này.

Để sử dụng một asynctask để thêm lớp này vào cuối hoạt động của bạn:

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);
  }
}

Và gọi từ phương thức onCreate () của bạn bằng cách sử dụng:

new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
        .execute(MY_URL_STRING);

Đừng quên thêm quyền dưới đây vào tệp kê khai của bạn

<uses-permission android:name="android.permission.INTERNET"/>

Làm việc tuyệt vời cho tôi. :)


2
Tôi thích giải pháp này, bạn chỉ cần dọn sạch mã cho onPostExecute, vì nó đã hết.
Sofija

điều đó thật tuyệt. @Sofija bạn có ý gì với việc dọn dẹp? Điều gì nếu bạn không biết số lượng hình ảnh?
5er

@ 5er Tôi đã có một số dấu ngoặc ngoài vị trí trong câu trả lời ban đầu. Kể từ khi tôi dọn dẹp nó, bạn sẽ có thể sử dụng nó như vậy.
Kyle Clegg

Đừng quên rằng chúng ta cũng cần thêm quyền trong tệp kê khai: <
used

1
Điều này thật tuyệt vời cho việc học / hack (upvote) nhưng đối với bất kỳ hoạt động sản xuất nào, bạn nên sử dụng thư viện Imageloader, có rất nhiều thứ ngoài đó. Người yêu thích của tôi là Trình tải hình ảnh phổ quát, Picasso, v.v.
AmeyaB

31

cố gắng picasssotốt đẹp và kết thúc trong một tuyên bố

Picasso.with(context)
                .load(ImageURL)
                .resize(width,height).into(imageView);

hướng dẫn: https://youtu.be/DxRqxsEPc2s


3
Picasso, Glide là yêu thích của tôi, cũng. Tuyên bố của Glide khá giống với Picasso, với nhiều cải tiến về kích thước bộ đệm.
anhtuannd

Đây phải là câu trả lời mới, mặc dù thật tuyệt khi biết cách tự làm. Bài viết tuyệt vời giải thích cả hai cách: Medium.com/@crossphd/ Mạnh
Martin Jäkel

9

Hãy thử điều này thêm tập tin lib pic picasso

Picasso.with(context)
                .load(ImageURL)
                .resize(width,height).noFade().into(imageView);

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


    }


}

trong hoạt động của bạn, hãy xem hình ảnh & đặt tài nguyên imageD Download (url, yourImageview);


5

UrlImageViewHelper sẽ lấp đầy ImageView bằng một hình ảnh được tìm thấy tại một URL. UrlImageViewHelper sẽ tự động tải xuống, lưu và lưu trữ tất cả các hình ảnh url của BitmapDrawables. Các url trùng lặp sẽ không được tải vào bộ nhớ hai lần. Bộ nhớ bitmap được quản lý bằng cách sử dụng bảng băm tham chiếu yếu, vì vậy ngay khi hình ảnh không còn được bạn sử dụng nữa, nó sẽ được thu gom rác tự động.

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

https://github.com/koush/UrlImageViewHelper


4

Dựa trên câu trả lời này, tôi viết trình tải của riêng tôi.

Với hiệu ứng Đang tải và Hiệu ứng xuất hiện:

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;
    }
}

Thêm quyền

<uses-permission android:name="android.permission.INTERNET"/>

Và thực hiện:

 new DownloadImageTask(context, imageViewToLoad, urlToImage).execute();

4

Đây là mã mẫu để hiển thị Hình ảnh từ 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();
        }
    }

3

Phương pháp tốt nhất tôi đã thử thay vì sử dụng bất kỳ thư viện

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;
    }
}

3

thêm sự cho phép của Internet

<uses-permission android:name="android.permission.INTERNET" />

hơn là tạo methode như dưới đây,

 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;
    }
}

Bây giờ thêm điều này trong phương thức onCreate của bạn,

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


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

đây là công việc cho tôi


2

Mã dưới đây chỉ cho bạn cách đặt ImageView từ chuỗi url, sử dụng RxAndroid. Đầu tiên, thêm thư viện 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'

}

bây giờ sử dụng setImageFromUrl để đặt hình ảnh.

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);
            }
        });
}

2

Có hai cách:

1) Sử dụng thư viện Glide Đây là cách tốt nhất để tải hình ảnh từ url bởi vì khi bạn cố gắng hiển thị cùng một url trong lần thứ hai, nó sẽ hiển thị từ bắt để cải thiện hiệu suất ứng dụng

Glide.with(context).load("YourUrl").into(imageView);

phụ thuộc: implementation 'com.github.bumptech.glide:glide:4.10.0'


2) Sử dụng luồng. Ở đây bạn muốn tạo bitmap từ hình ảnh url

URL url = new URL("YourUrl");
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);

1
loadImage("http://relinjose.com/directory/filename.png");

Bạn đi đây

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
    }
}

Có gì ivdpfirst?
Big McLUNDHuge

Id của ImageView được sử dụng trong thiết kế xml.
Đặc biệt

1

Thử cái này:

InputStream input = contentResolver.openInputStream(httpuri);
Bitmap b = BitmapFactory.decodeStream(input, null, options);

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);
        }
    }
}

1

Đối với tôi, Fresco là tốt nhất trong số các thư viện khác.

Chỉ cần thiết lập Fresco và sau đó chỉ cần đặt imageURI như thế này:

draweeView.setImageURI(uri);

Kiểm tra câu trả lời này giải thích một số lợi ích của Fresco.

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.