android下载图像到SD卡,然后从SD卡读取它

时间:2011-04-23 19:37:12

标签: android download save sd-card

嗨所有我有我的代码的这个问题,我尝试了所有我知道的东西,我发布在一些论坛上,并没有得到一个新的答案,我还在学习......

我的问题是我有一个代码,假设接收一个变量,其中包含一个有图像的网站,所以这个变量每次发送新链接时都会更改,此代码应该联机并下载图像并将其保存到sd-card然后我读它并显示它

所以我的代码问题是如果我发送2个链接,它下载1个图像,它总是用第二个图像名称存储它(例如:im发送image1和image2代码下载image1两次并存储它作为“image2”)当我挂载SD卡并检查图像目录时,只有1个图像名为image2, 我认为doInBackground导致问题,但我也使用onPostExecute() 所以,如果有人能帮助我,我会感谢他的帮助 请注意,这就是我所说的:

locLink = getLocalLink(buffer[3], buffer[0]);

buffer[3] = image website (example:http://www.oceanwideimages.com/images/7049/large/24M2444-16-palm-fringed-tropical-island.jpg)

buffer[0] = new file name (example 1 as a string)

这是代码:

private class DownloadImageTask extends AsyncTask<URL, Integer, Bitmap> {
        // This class definition states that DownloadImageTask will take String
        // parameters, publish Integer progress updates, and return a Bitmap
        protected Bitmap doInBackground(URL... paths) {
            URL url;
            try {
                url = paths[0];
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                int length = connection.getContentLength();
                InputStream is = (InputStream) url.getContent();
                byte[] imageData = new byte[length];
                int buffersize = (int) Math.ceil(length / (double) 100);
                int downloaded = 0;
                int read;
                while (downloaded < length) {
                    if (length < buffersize) {
                        read = is.read(imageData, downloaded, length);
                    } else if ((length - downloaded) <= buffersize) {
                        read = is.read(imageData, downloaded, length
                                - downloaded);
                    } else {
                        read = is.read(imageData, downloaded, buffersize);
                    }
                    downloaded += read;
                    publishProgress((downloaded * 100) / length);
                }
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
                        length);
                if (bitmap != null) {
                    Log.i(TAG, "Bitmap created");
                } else {
                    Log.i(TAG, "Bitmap not created");
                }
                is.close();
                return bitmap;
            } catch (MalformedURLException e) {
                Log.e(TAG, "Malformed exception: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e.toString());
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.toString());
            }
            return null;

        }

        protected void onPostExecute(Bitmap result) {
            String name = ImageLink.substring(ImageLink
                    .lastIndexOf("/") + 1);
            if (result != null) {
                hasExternalStoragePublicPicture(name);
                saveToSDCard(result, name);
                isImage = true;

            } else {
                isImage = false;

            }
        }
    }

    public void saveToSDCard(Bitmap bitmap, String name) {
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mExternalStorageAvailable = mExternalStorageWriteable = true;
            Log.v(TAG, "SD Card is available for read and write "
                    + mExternalStorageAvailable + mExternalStorageWriteable);
            saveFile(bitmap, name);
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
            Log.v(TAG, "SD Card is available for read "
                    + mExternalStorageAvailable);
        } else {
            mExternalStorageAvailable = mExternalStorageWriteable = false;
            Log.v(TAG, "Please insert a SD Card to save your image "
                    + mExternalStorageAvailable + mExternalStorageWriteable);
        }
    }

    private void saveFile(Bitmap bitmap, String name) {

        String filename = name;
        ContentValues values = new ContentValues();
        File sdImageMainDirectory = new File(Environment
                .getExternalStorageDirectory(), getResources().getString(
                R.string.directory));
        sdImageMainDirectory.mkdirs();
        File outputFile = new File(sdImageMainDirectory, filename);
        values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
        values.put(MediaStore.MediaColumns.TITLE, filename);
        values.put(MediaStore.MediaColumns.DATE_ADDED, System
                .currentTimeMillis());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        Uri uri = this.getContentResolver().insert(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,

                values);
        try {
            OutputStream outStream = this.getContentResolver()
                    .openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream);

            outStream.flush();
            outStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean hasExternalStoragePublicPicture(String name) {
        File sdImageMainDirectory = new File(Environment
                .getExternalStorageDirectory(), getResources().getString(
                R.string.directory));
        File file = new File(sdImageMainDirectory, name);
        if (file != null) {
            file.delete();
        }

        return file.exists();
    }

这就是我读它的方式:

String imageInSD = c.getString(5); //"/sdcard/Hanud/image1.jpg"or image2;
            Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
            myImageView=(ImageView)findViewById(R.id.imageview1);
            myImageView.setImageURI(null);
            myImageView.setImageBitmap(bitmap);

0 个答案:

没有答案
相关问题