Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/218.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android:从url下载大型图像文件(最大2MB)_Android - Fatal编程技术网

Android:从url下载大型图像文件(最大2MB)

Android:从url下载大型图像文件(最大2MB),android,Android,我想从url下载大型图像文件,但当我尝试解码输入流时,它抛出了内存不足错误。图像文件大小约为2mb 如何下载大型图像文件并在图像视图中显示?使用此类,它工作正常 import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Colle

我想从url下载大型图像文件,但当我尝试解码输入流时,它抛出了内存不足错误。图像文件大小约为2mb


如何下载大型图像文件并在图像视图中显示?

使用此类,它工作正常

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;





public class DrawableBackgroundDownloader {    

private final Map<String, Drawable> mCache = new HashMap<String, Drawable>();   
private final LinkedList <Drawable> mChacheController = new LinkedList <Drawable> ();
private ExecutorService mThreadPool;  
private final Map<ImageView, String> mImageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());  
public static int MAX_CACHE_SIZE = 80; 
public int THREAD_POOL_SIZE = 3;



/**
 * Constructor
 */
public DrawableBackgroundDownloader() {  
    mThreadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);  
}  


/*
 * Clears all instance data and stops running threads
*/ 
public void Reset() {
    ExecutorService oldThreadPool = mThreadPool;
    mThreadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    oldThreadPool.shutdownNow();

    mChacheController.clear();
    mCache.clear();
    mImageViews.clear();
}  

public void loadDrawable(final String url, final ImageView imageView,Drawable placeholder) {  
    if(!mImageViews.containsKey(url))
        mImageViews.put(imageView, url);  
    Drawable drawable = getDrawableFromCache(url);  

    // check in UI thread, so no concurrency issues  
    if (drawable != null) {  
        //Log.d(null, "Item loaded from mCache: " + url);  
        imageView.setImageDrawable(drawable);  
    } else {  
        imageView.setImageDrawable(placeholder);  
        queueJob(url, imageView, placeholder);  
    }  
} 



public Drawable getDrawableFromCache(String url) {  
    if (mCache.containsKey(url)) {  
        return mCache.get(url);  
    }  

    return null;  
}

private synchronized void putDrawableInCache(String url,Drawable drawable) {  
    int chacheControllerSize = mChacheController.size();
    if (chacheControllerSize > MAX_CACHE_SIZE) 
        mChacheController.subList(0, MAX_CACHE_SIZE/2).clear();

    mChacheController.addLast(drawable);
    mCache.put(url, drawable);

}  

private void queueJob(final String url, final ImageView imageView,final Drawable placeholder) {  
    /* Create handler in UI thread.  */
    final Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            String tag = mImageViews.get(imageView);  
            if (tag != null && tag.equals(url)) {
                if (imageView.isShown())
                    if (msg.obj != null) {
                        imageView.setImageDrawable((Drawable) msg.obj);  
                    } else {  
                        imageView.setImageDrawable(placeholder);  
                        //Log.d(null, "fail " + url);  
                    } 
            }  
        }  
    };  

    mThreadPool.submit(new Runnable() {  
        public void run() {  
            final Drawable bmp = downloadDrawable(url);
            // if the view is not visible anymore, the image will be ready for next time in cache
            if (imageView.isShown())
            {
                Message message = Message.obtain();  
                message.obj = bmp;
                //Log.d(null, "Item downloaded: " + url);  

                handler.sendMessage(message);
            }
        }  
    });  
}  



private Drawable downloadDrawable(String url) {  
    try {  
        InputStream is = getInputStream(url);

        Drawable drawable = Drawable.createFromStream(is, url);
        putDrawableInCache(url,drawable);  
        return drawable;  

    } catch (MalformedURLException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  

    return null;  
}  


private InputStream getInputStream(String urlString) throws MalformedURLException, IOException {
    URL url = new URL(urlString);
    URLConnection connection;
    connection = url.openConnection();
    connection.setUseCaches(true); 
    connection.connect();
    InputStream response = connection.getInputStream();

    return response;
}
}
您可以编辑以调整大小:

 mThreadPool.submit(new Runnable() {  
            public void run() {  
                final Drawable bmp = downloadDrawable(url);
                // if the view is not visible anymore, the image will be ready for next time in cache
                if (imageView.isShown())
                {
                    Message message = Message.obtain();  
                    message.obj = bmp;
                    //Log.d(null, "Item downloaded: " + url);  

                    handler.sendMessage(message);
                }
            }  
        });  
    } 
调整大小:

查看此


最好将其与Asynctask或thread一起使用,先将其保存到文件中,然后使用BitmapFactory选项缩小图像比例,我希望显示原始图像。一个也没有!不过,请先将其保存到光盘。那么,您的屏幕和图像的分辨率是多少?我的设备分辨率是480x800。我已经实现了收缩缩放,我想用收缩图像视图显示图像。这就是为什么我使用服务器端的高分辨率图像。
 mThreadPool.submit(new Runnable() {  
            public void run() {  
                final Drawable bmp = downloadDrawable(url);
                // if the view is not visible anymore, the image will be ready for next time in cache
                if (imageView.isShown())
                {
                    Message message = Message.obtain();  
                    message.obj = bmp;
                    //Log.d(null, "Item downloaded: " + url);  

                    handler.sendMessage(message);
                }
            }  
        });  
    } 
try {
        URL url = new URL("image download url");
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream("/sdcard/image_name.extension");

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....                
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {
    }
    return null;