简体   繁体   English

从Android中的网址下载图片

[英]Download Image from an url in Android

I have to download an image from an url. 我必须从网址下载图片。 Do you recommend Bitmap or Drawable? 您推荐位图还是可绘制? Whatever, I have tried twice, but those don't work. 不管怎样,我已经尝试了两次,但是这些都不起作用。 Do you know what could be the problem?? 你知道可能是什么问题吗? (I have written the internet and the external storage permissions). (我已经写了Internet和外部存储权限)。 You will see that I recieve the URL by a JSON object, but I was recieved correctly. 您将看到我通过JSON对象接收了URL,但是我正确地接收了该URL。

If I want to recieve it in a Drawable element: 如果我想在Drawable元素中接收它:

protected Drawable getDrawable()
    {
        try{
            JSONObject jsonResponse = new JSONObject(content);
            String src=jsonResponse.getString(data);
            InputStream is = (InputStream)new URL(src).getContent();
            Drawable d=Drawable.createFromStream(is, "basket.png");
            return d;
        }
        catch(Exception e)
        {
            String err="This is the error: ";
            Log.e(err,e.getMessage());
            //e.printStackTrace();
            return null;
        }
    }

If I want to recieve it un a Bitmap element: 如果我想接收它的位图元素:

protected Bitmap getBitMap()
    {
        try{
            JSONObject jsonResponse = new JSONObject(content);
            String src=jsonResponse.getString(data);
            java.net.URL url = new java.net.URL(src);
            HttpURLConnection con=(HttpURLConnection)url.openConnection();
            con.setDoInput(true);
            con.connect();
            InputStream input=con.getInputStream();
            Bitmap myBitmap=BitmapFactory.decodeStream(input);
            return myBitmap;
        }
        catch(Exception e){
            String err="This is the error: ";
            Log.e(err,e.getMessage());
            //e.printStackTrace();
            return null;
        }
    }

This is where I have the ImageView: 这是我拥有ImageView的位置:

public class Accedido extends AppCompatActivity {

    ImageView imagen;
    Button ok;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_accedido);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        imagen=(ImageView)findViewById(R.id.Img);
        ok=(Button)findViewById(R.id.btnOk);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap img=null;
                Ajax im=new Ajax();
                try {
                    String imagen = im.execute(MainActivity.IP_ADDRESS + "Imagen").get();
                    LeerConsulta lec = new LeerConsulta(imagen, "img");
                    //img=lec.getBitMap();
                    /*String res=lec.getContent();
                    String res2=lec.getData();
                    Toast.makeText(Accedido.this, "Content:"+res+"Data:"+res2, Toast.LENGTH_LONG).show();*/
                    img=lec.getBitMap();
                }
                catch(Exception exc) {
                    Toast.makeText(Accedido.this, exc.getMessage(), Toast.LENGTH_SHORT).show();
                }
                imagen.setImageBitmap(img);
            }
        });
    }

When I run those codes, the program throws me an error which says println needs a message ...But I have never written in the program a system.out.println 当我运行这些代码时,程序抛出一个错误,提示println needs a message ...但是我从未在程序中编写过system.out.println

use Asynck task to download image . 使用Asynck任务下载图像。

 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 mIcon = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }

You can refer this link http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/ 您可以参考此链接http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/

Bitmap is better in my opinion. 我认为位图更好。 Try this out. 试试看 Make sure that the URL you get from the JSON is only of image. 确保从JSON获得的URL仅是图像。

JSONObject jsonResponse = new JSONObject(content);
String src=jsonResponse.getString(data);
java.net.URL url = new java.net.URL(src);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());

Moreover, Universal Image Loader library is also available. 此外,还提供Universal Image Loader库。 Try that as well. 也尝试一下。

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley是一个HTTP库,可简化Android应用程序的联网,最重要的是,可以更快地联网。 At a high level, you use Volley by creating a RequestQueue and passing it Request objects. 在较高的级别上,您可以通过创建RequestQueue并将其传递给Request对象来使用Volley。 The RequestQueue manages worker threads for running the network operations, reading from and writing to the cache, and parsing responses. RequestQueue管理工作线程以运行网络操作,读取和写入缓存以及解析响应。

You can use Volley for Image downloading: 您可以使用Volley进行图像下载:

Add repo in your Gradle: 在您的Gradle中添加回购:

compile 'com.android.volley:volley:1.0.0'

You need to add this code, in your class where ImageView is present, just add the code (In download button if you have any): 您需要在存在ImageView的类中添加以下代码,只需添加代码(如果有的话,在下载按钮中):

ImageRequest imageRequest = new ImageRequest(your_image_url, new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(final Bitmap response) {
                    your_image_view.setImageBitmap(response);
        }
    }, 0, 0, ImageView.ScaleType.CENTER_INSIDE, null, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(your_activity_context.this, error.toString(), Toast.LENGTH_LONG).show();
        }
    });

    RequestQueue requestQueue = Volley.newRequestQueue(your_activity_context.this);
    requestQueue.add(imageRequest);

Courtesy Google.com Google.com提供

您可以使用Glide库将图像直接从URL下载到图像视图中。

Glide.with(context).load(url).diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM