โหลดภาพจาก url


156

ฉันมี URL ภาพ ฉันต้องการแสดงภาพจาก URL นี้ใน ImageView แต่ไม่สามารถทำได้

สิ่งนี้จะสำเร็จได้อย่างไร


เป็นไปได้ที่ซ้ำกันของวิธีการโหลด ImageView ด้วย URL ใน Android?
blahdiblah

ดูคำถามเหล่านี้และมุ่งเน้นไปที่คำตอบแรกที่นี่คุณสามารถหาสองวิธีที่ง่ายและสมบูรณ์ในการทำเช่นนี้: วิธีแรก (สมบูรณ์มากขึ้น)หรือวิธีที่สอง (ง่ายขึ้น)
lory105

คุณสามารถใช้ Picasso และฉุยฉายโหลดภาพและแสดงให้ IMAGE ดู
shweta ค

คำตอบ:


240
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
คุณไม่ควรใช้สิ่งนี้เพราะจะบล็อกเธรด UI ห้องสมุดนี้จะจัดการเธรดและดาวน์โหลดให้คุณ: github.com/koush/UrlImageViewHelper
koush

16
ไม่ใช่ถ้าคุณเรียกใช้บล็อกนั้นในเธรดแยกต่างหากลบ setImageBitmap
Jonathan

มันทำงานได้ฉันแสดงในรูปขนาดย่อและ onclick imageview ฉันใช้ dailog dsplaying แต่มันจะเปิดขึ้นหลังจาก 10secs
Prasad

4
@koush - AsyncTaskรหัสนี้จะดีถ้าห่อ
Greg Brown

2
คุณควรทำการดำเนินการ networl ในเธรดแยกต่างหากเมื่อโหลดบิตแมปแล้วคุณสามารถใช้ ImageView.post () หรือ Handler.post ()
Volodymyr Shalashenko

311

คำตอบที่ได้รับการยอมรับด้านบนนั้นยอดเยี่ยมหากคุณกำลังโหลดรูปภาพโดยคลิกปุ่ม แต่ถ้าคุณทำในกิจกรรมใหม่มันจะหยุดค้าง 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);

อย่าลืมเพิ่มสิทธิ์ด้านล่างในไฟล์ Manifest ของคุณ

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

ใช้งานได้ดีสำหรับฉัน :)


2
ฉันชอบโซลูชันนี้คุณควรล้างโค้ดสำหรับ onPostExecute เนื่องจากเป็นส่วนของเนื้อหา
Sofija

มันเยี่ยมมาก @Sofija คุณหมายถึงอะไรกับการทำความสะอาด? ถ้าคุณมีจำนวนรูปภาพที่ไม่รู้จักล่ะ?
5er

@ 5er ฉันมีบางส่วนของวงเล็บออกจากสถานที่ในคำตอบเดิม ฉันได้ทำความสะอาดมันมาแล้วดังนั้นคุณควรจะใช้มันตามที่เป็นอยู่
Kyle Clegg

อย่าลืมว่าเราต้องเพิ่มการอนุญาตในรายการ: <การใช้งานการอนุญาต android: name = "android.permission.INTERNET" />
mike20132013

1
สิ่งนี้ยอดเยี่ยมสำหรับการเรียนรู้ / การแฮ็ก (upvoted) แต่สำหรับการผลิตอะไรก็ตามคุณควรใช้ไลบรารี Imageloader ซึ่งมีอยู่มากมาย คนที่ฉันชอบคือ Universal Image loader, Picasso และอื่น ๆ อีกมากมาย
AmeyaB

31

ลองpicasssoดีและเสร็จสิ้นในหนึ่งคำสั่ง

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

บทช่วยสอน: https://youtu.be/DxRqxsEPc2s


3
Picasso, Glide เป็นรายการโปรดของฉันด้วย แถลงการณ์ของ Glide นั้นค่อนข้างคล้ายกับ Picasso โดยมีการปรับปรุงขนาดแคชมากขึ้น
anhtuannd

1
นี่ควรเป็นคำตอบใหม่แม้ว่าจะเป็นเรื่องดีที่จะรู้ว่าจะทำอย่างไรด้วยตัวคุณเอง บทความที่ดีอธิบายทั้งสองวิธี: medium.com/@crossphd/…
Martin Jäkel


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 & set ทรัพยากร imageDownload (url, yourImageview);


5

UrlImageViewHelper จะเติม ImageView ด้วยรูปภาพที่พบได้ใน URL UrlImageViewHelper จะดาวน์โหลดบันทึกและแคชรูปภาพทั้งหมดโดยอัตโนมัติที่เรียกว่า BitmapDrawables URL ซ้ำจะไม่ถูกโหลดในหน่วยความจำสองครั้ง หน่วยความจำบิตแมปได้รับการจัดการโดยใช้ตารางแฮชอ้างอิงอ่อนดังนั้นทันทีที่คุณไม่ใช้รูปภาพอีกต่อไปรูปภาพจะถูกรวบรวมโดยอัตโนมัติ

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

https://github.com/koush/UrlImageViewHelper


4

จากคำตอบนี้ฉันเขียนตัวโหลดของฉันเอง

ด้วยเอฟเฟกต์การโหลดและเอฟเฟกต์ปรากฏ:

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

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

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

3

เพิ่มสิทธิ์อินเทอร์เน็ตในไฟล์ Manifest

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

กว่าสร้าง methode ดังต่อไปนี้

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

ตอนนี้เพิ่มสิ่งนี้ในวิธีการสร้างของคุณ

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


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

มันใช้งานได้สำหรับฉัน


2

รหัสด้านล่างแสดงวิธีตั้งค่า ImageView จากสตริง url โดยใช้ RxAndroid ก่อนอื่นให้เพิ่ม RxAndroid library 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);
            }
        });
}

2

มีสองวิธี:

1) การใช้ Glide libraryวิธีนี้เป็นวิธีที่ดีที่สุดในการโหลดภาพจาก url เพราะเมื่อคุณพยายามที่จะแสดง url เดียวกันในครั้งที่สองมันจะแสดงผลจาก catch เพื่อปรับปรุงประสิทธิภาพของแอพ

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

การพึ่งพา: 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);

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

อะไรนะivdpfirst?
Big McLargeHuge

รหัสของ ImageView ที่ใช้ในการออกแบบ xml
พิเศษ

1

ลองสิ่งนี้:

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

สำหรับฉันFrescoนั้นดีที่สุดในบรรดาห้องสมุดอื่น ๆ

เพียงแค่เซ็ตอัพเฟรสโกแล้วตั้งค่าภาพต่อไปนี้

draweeView.setImageURI(uri);

ลองอ่านคำตอบนี้เพื่ออธิบายถึงประโยชน์ของปูนเปียก

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.