简体   繁体   English

将图像从图像URL下载到图像视图

[英]Download Image From Image URL to image view

i am trying to download image from imageurl the image comming from that url is a high resolution image.it is working fine in all high resolution phones when i tried to load this image in to a an emulator of mdpi it is throwing out of memory leak exception. 我正在尝试从imageurl下载图像,从该URL传来的图像是高分辨率image。当我尝试将此图像加载到mdpi的仿真器中时,它在所有高分辨率手机中均正常工作,这会导致内存泄漏例外。

how can i handle this situation and i want this image in each and every screen so i am declaring bitmap as a global variable 我该如何处理这种情况,并且我希望每个屏幕上都有此图像,所以我将位图声明为全局变量

is there any way to reduce the image size while downloading. 有什么方法可以减小下载时的图像大小。 iam using the below code to download an image iam使用以下代码下载图像

c1 is the reference to image view c1是图像视图的参考

bitmap = BitmapFactory.decodeStream((InputStream)new URL(logourltop.get(0)).getContent());
cl.setImageBitmap(bitmap) ;

(or) (要么)

it is better to use urlimagehelper project to download an image whenever required 最好在需要时使用urlimagehelper项目下载图像

UrlImageViewHelper.setUrlDrawable(cl,logourltop.get(0));

and one more doubt is i am changing the views in the same activity by using 还有一个疑问是我正在通过使用以下命令更改同一活动中的视图

setContentView(R.layout.filename).

if i change the view on listitem click the memory allocated for the bitmap will be released or not.(The memory allocated for objects and bitmaps for that view) 如果我在listitem上更改视图,请单击是否释放为位图分配的内存。(为该视图分配给对象和位图的内存)

can you please suggest me a better way to avoid memory leaks. 你能建议我一个更好的方法来避免内存泄漏。

You basically have to download the image data and with the image data in form of a stream or a byte array, you can use the convenience methods from BitmapFactory that will give you a Bitmap out of it, and with this Bitmap in hands, you can already set it directly to the ImageView. 基本上,您必须下载图像数据,并以流或字节数组的形式保存图像数据,您可以使用BitmapFactory中的便捷方法,该方法将为您提供一个位图,并且可以使用此位图来进行操作已经直接将其设置为ImageView。

Make sure you perform the download from the network in a separated Thread eg using AsyncTask .doInBackground() and set the Bitmap on the ImageView on the UI thread eg by setting it on the method onPostExecute() of the AsyncTask or calling Activity.runOnUIThread() . 请确保您执行在使用独立的线程例如网络下载的AsyncTask .doInBackground() ,并设置位图上,例如通过设置它的方法在UI线程的ImageView的onPostExecute()中的AsyncTask或致电Activity.runOnUIThread( )

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class downloadimg extends Activity {

//  
private ImageView mImageView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Find the reference to the ImageView
    mImageView = (ImageView) findViewById(R.id.test_image);

    // You can set a temporary background here
    //image.setImageResource(null);

    // Start the DownloadImage task with the given url
    new DownloadImage().execute("http://demo.imgur.com/CQzlM.jpg");
}


/**
 * Simple functin to set a Drawable to the image View
 * @param drawable
 */
private void setImage(Drawable drawable)
{
    mImageView.setBackgroundDrawable(drawable);
}

public class DownloadImage extends AsyncTask<String, Integer, Drawable> {

    @Override
    protected Drawable doInBackground(String... arg0) {
        // This is done in a background thread
        return downloadImage(arg0[0]);
    }

    /**
     * Called after the image has been downloaded
     * -> this calls a function on the main thread again
     */
    protected void onPostExecute(Drawable image)
    {
        setImage(image);
    }


    /**
     * Actually download the Image from the _url
     * @param _url
     * @return
     */
    private Drawable downloadImage(String _url)
    {
        //Prepare to download image
        URL url;        
        BufferedOutputStream out;
        InputStream in;
        BufferedInputStream buf;

        //BufferedInputStream buf;
        try {
            url = new URL(_url);
            in = url.openStream();



            // Read the inputstream 
            buf = new BufferedInputStream(in);

            // Convert the BufferedInputStream to a Bitmap
            Bitmap bMap = BitmapFactory.decodeStream(buf);
            if (in != null) {
                in.close();
            }
            if (buf != null) {
                buf.close();
            }

            return new BitmapDrawable(bMap);

        } catch (Exception e) {
            Log.e("Error reading file", e.toString());
        }

        return null;
    }

}

}

Hope this will help... 希望这会有所帮助...

public class BitmapResizer {

    public static Bitmap decodeFile(File f,int requiredSize){
    try {
        //decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE=requiredSize;
        int width_tmp=o.outWidth, height_tmp=o.outHeight;
        int scale=1;
        while(true){
            if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                break;
            width_tmp/=2;
            height_tmp/=2;
            scale*=2;
        }

        //decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {

    }
    return null;
}}

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

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