有效地加载位图

时间:2012-11-02 05:22:13

标签: android memory bitmap

我正在通过developer.android页面有效地加载位图,在这里:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html他们谈论将缩小版本加载到内存中,这显然非常有效。

现在我的问题是,在从互联网下载图像/位图时,给定的方法需要资源的ID,我们不会得到(如果我错了,请纠正我)。

那么我们有什么办法可以对从互联网上下载的图像使用给定方法的一些变化吗?

1 个答案:

答案 0 :(得分:0)

嘿我不知道这个方法,但这是我从互联网上下载图像并保存到SD卡你可以根据你的要求使用它我使用保存的方法保存图片

public class fetchImage extends Activity implements OnClickListener {
    int id;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = 1;// declaring static as of now

    }

    {

        new BackgroundTask().execute();
        File storagePath = Environment.getExternalStorageDirectory();
        File imgFile = new File(storagePath, "/Pictures/" + id + ".jpg");

        if (imgFile.exists()) {
            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
                    .getAbsolutePath());
        }

    }

    class BackgroundTask extends AsyncTask<Void, Void, Void> {
        ProgressDialog mDialog;

        protected void onPreExecute() {
            mDialog = ProgressDialog.show(fetchImage.this, "",
                    getString(R.string.progress_bar_loading), true);
        };

        @Override
        protected Void doInBackground(Void... params) {
            try {

                savesd(id, null);

            } catch (final Exception e) {

            }
            return null;
        }

        private void savesd(int id, URL uri) throws IOException {
            URL url;
            if (uri == null) {
                url = new URL("http://i.zdnet.com/blogs/3-29-androids.jpg");
            } else {
                url = uri;
            }
            InputStream input = url.openStream();
            try {
                File storagePath = Environment.getExternalStorageDirectory();
                OutputStream output = new FileOutputStream(new File(
                        storagePath, "/Pictures/" + id + ".jpg"));
                try {
                    byte[] buffer = new byte[20000];
                    int bytesRead = 0;
                    while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                        output.write(buffer, 0, bytesRead);
                    }
                } finally {
                    output.close();
                }
            } catch (Exception e) {

                e.printStackTrace();
            } finally {
                input.close();
            }

        }

        protected void onPostExecute(Void result) {
            mDialog.dismiss();
        };
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

}