Android:从URL读取图像

时间:2011-06-30 07:20:14

标签: android url

在看完net的所有示例之后,我编写了以下代码来从URL中读取图像,将其显示到图像视图并将其保存到指定的路径。         公共课下载{

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


    }
}

现在的问题是这个代码有时有效并且有时会失败......错误是

    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

并且有时候得到          SkImageDecoder :: Factory返回null。

帮助我解决可能的原因

2 个答案:

答案 0 :(得分:1)

考虑这个例子,它展示了如何从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);

答案 1 :(得分:0)

您应该在连接失败时执行重试。