安卓:从图像读取URL [英] Android: Image Reading from URL

查看:190
本文介绍了安卓:从图像读取URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到净所有的例子后,我写了follwoing code从URL读取图像,显示它图像视图并将其保存到指定的路径。
        公共类下载{

After seeing all the examples from net, i have written the follwoing code to read an image from the URL, show it to the Image view and save it to the path specified. public class Downloader {

public void startDownload(ImageView i, String path,String url){

    BitmapDownloaderTask task = new BitmapDownloaderTask(i,path);
    task.execute(url,null,null);
}
    static class FlushedInputStream extends FilterInputStream {
    public FlushedInputStream(InputStream inputStream) {
        super(inputStream);
    }

    @Override
    public long skip(long n) throws IOException {
        long totalBytesSkipped = 0L;
        while (totalBytesSkipped < n) {
            long bytesSkipped = in.skip(n - totalBytesSkipped);
            if (bytesSkipped == 0L) {
                  int b = read();
                  if (b < 0) {
                      break;  // we reached EOF
                  } else {
                      bytesSkipped = 1; // we read one byte
                  }
           }
            totalBytesSkipped += bytesSkipped;
        }
        return totalBytesSkipped;
    }
}
static Bitmap downloadBitmap(String url) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) { 
            Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent(); 
                final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
                return bitmap;
            } finally {
                if (inputStream != null) {
                    inputStream.close();  
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {
        // Could provide a more explicit error message for IOException or IllegalStateException
        getRequest.abort();
        System.err.println("Error while retrieving bitmap from " + url +":"+ e.toString());
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}
private class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
    private String url;
    private final WeakReference<ImageView> imageViewReference;
    private String path;
    public BitmapDownloaderTask(ImageView imageView, String FilePath) {
        imageViewReference = new WeakReference<ImageView>(imageView);
        path = FilePath;
    }

    @Override
    // Actual download method, run in the task thread
    protected Bitmap doInBackground(String... params) {
         // params comes from the execute() call: params[0] is the url.
         return downloadBitmap(params[0]);
    }

    @Override
    // Once the image is downloaded, associates it to the imageView
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }

        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
        OutputStream outStream = null;
        File file = new File(path);
        try {
         outStream = new FileOutputStream(file);
         bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
         outStream.flush();
         outStream.close();
        }
        catch(Exception e)
        {}


    }
}

现在的问题是这样的code工作有时有有时失败...误差

Now the problem is this code works sometimes and fails sometimes... the error is

    06-30 12:34:23.363: WARN/System.err(16360): Error while retrieving bitmap from https://URL IS HERE---REMOVE FOR PRIVACY:java.net.SocketTimeoutException: Read timed out

和一段时间得到
         SkImageDe codeR ::厂返回null。

and some time a get SkImageDecoder::Factory returned null.

帮助我的可能原因

推荐答案

考虑这个例子的展示了如何创建网址图片

consider this example its show how to create image from url

               URL url = new URL(Your Image URL In String); 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap  myBitmap = BitmapFactory.decodeStream(input);
             yourImageView.setImageBitmap(myBitmap);

这篇关于安卓:从图像读取URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆