【问题标题】:Android: download large image file from url (up to 2 mb)Android:从 url 下载大图像文件(最大 2 mb)
【发布时间】:2013-01-14 04:15:39
【问题描述】:

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

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

【问题讨论】:

  • 先保存到文件,然后使用BitmapFactory选项缩小图片
  • 我想显示原始图像。没有缩放一个!
  • 仍然,先将其保存到光盘。那么,您的屏幕和图像的分辨率是多少?
  • 我的设备分辨率是 480x800 。我已经实现了捏缩放,我想用捏图像视图显示图像。这就是为什么我使用服务器端的高分辨率图像。

标签: android


【解决方案1】:

看看这个Download a file with Android, and showing the progress in a ProgressDialog

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;

最好将它与 Asynctask 或线程一起使用

【讨论】:

    【解决方案2】:

    使用这个类就可以了。

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

    使用示例:

    DrawableBackgroundDownloader drawableDownloader = new DrawableBackgroundDownloader(); //as a field in your class
    ImageView iView // ImageView to assign the drawable
    Drawable drawable // The drawable that will show during the image is loading.
    drawableDownloader.loadDrawable("htttp://asd.com/img.jpg", iView,drawable);
    

    您可以编辑以调整大小:

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

    调整大小:Resize Drawable in Android

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多