0

有人可以告诉我这段代码哪里出错了吗?基本上我希望应用程序下载一个 .png 文件,将其显示给用户并将其保存到 sd 卡以供将来参考。直到部分似乎一切都很好while ((len = webstream.read(buffer)) > 0);因为调试器没有到达我放在这里的断点,而且我有一个空的 .png 文件目录。我有WRITE_EXTERNAL_STORAGE在我的清单中声明的​​许可。

protected class DownloadTask extends AsyncTask<String, Integer, Bitmap> {

    @Override
    protected Bitmap doInBackground(String... string) {

        Bitmap d = null;

        try {

            DefaultHttpClient dhc = new DefaultHttpClient();
            HttpGet request = new HttpGet(HTTP_BASE + string[0] + ".png");
            HttpResponse response = dhc.execute(request);
            BufferedInputStream webstream = new BufferedInputStream(response.getEntity().getContent());
            d = BitmapFactory.decodeStream(webstream);
            writeToSd(string[0], webstream, d);

        }
        catch (Exception ex) { ex.printStackTrace(); }

        return d;

    }

    private void writeToSd(String string, BufferedInputStream webstream, Bitmap d) {

        try {

            webstream.mark(3);
            webstream.reset();
            File f = new File(Environment.getExternalStorageDirectory() + SD_DIR);
            f.mkdirs();
            File f2 = new File(f, string + ".png");
            f2.createNewFile();
            BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(f2));

            int len;
            byte[] buffer = new byte[1024];
            while ((len = webstream.read(buffer)) > 0) {

                fos.write(buffer, 0, len);

            }

            webstream.close();
            //fos.flush();
            fos.close();

        }
        catch (Exception ex) {

            ex.printStackTrace();

        }


    }

    protected void onPostExecute(Bitmap result) {

        if (result != null) {
            iv.setImageBitmap(result);
            vs.setDisplayedChild(1);
        }

    }

};
4

2 回答 2

1

我不确定,但重新读取 InputStream 似乎有问题,即使它是缓冲的。图像是保存在内存中的大量数据。而不是做

获取图像、显示图像、存储图像

你可以尝试

获取图像、存储图像、显示图像

This way you can write a full-sized image to disk (without having to buffer the stream and consume a lot of memory). Then, you can simply load the image from the sd card at the lowest sampling rate that works for your application, thus saving having a full-sized image ever in memory. Also, doing it this way would likely eliminate any issues you may or may not be having with the bufferedInputStream - I find them to be pretty finicky.

于 2010-10-02T00:40:05.997 回答
1

Unless you want the original stream bytes, you can write the bitmap out to disk using Bitmap.compress(format, quality, stream).

However, Hamy's answer is probably best from a memory conservation point of view.

于 2010-10-02T01:20:28.053 回答