1

我正在尝试从 url 下载图像并将其存储在 sd 卡上,它适用于 .jpg 文件但如果图像扩展名是 .png 或 .jpeg 则它会出错,我想同时下载不同格式的图像时间..下面是我输入的代码..

 public void DownloadFromUrl(String DownloadUrl, String fileName) {

    try {
        File dir = new File("/sdcard/pluto");

        if (dir.exists() == false) {
            dir.mkdirs();
        }

        URL url = new URL(DownloadUrl); // you can write here any link
        File file = new File(dir, fileName);

        long startTime = System.currentTimeMillis();
        Log.d("DownloadManager", "download begining");
        Log.d("DownloadManager", "download url:" + url);
        Log.d("DownloadManager", "downloaded file name:" + fileName);

        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();

        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
        Log.d("DownloadManager",
                "download ready in"
                        + ((System.currentTimeMillis() - startTime) / 1000)
                        + " sec");

    } catch (IOException e) {
        Log.d("DownloadManager", "Error: " + e);
    }

}

请帮我..

4

1 回答 1

0

试试这个可能会有所帮助。

相同的帖子具有不同的图像格式。

图像下载代码适用于所有图像格式,PNG 格式呈现问题

于 2012-11-05T08:03:55.490 回答