android将图像保存两次到SD卡

时间:2011-04-20 04:46:39

标签: android image download sd-card

我有一个代码可以从网站下载图像并将其保存在SD卡上。 当我出于某种原因发送2个网址时,它只下载第一个图像2次,并用第二个图像名称保存它们,所以如果网站上有image1和image2,代码将只下载image1两次并保存在SD上-card as image2可以请别人告诉我我做错了什么?

public String getLocalLink(String image_URL, String imageName){
        /** This is what we do with this method:
         * Go online, according to the link, get the content, call the method to save.
         */

        ImageLink = image_URL;
        URL ImageLinkURL;

        try {
             ImageLinkURL = new URL(ImageLink);
            //URL url     = new URL(strURL);
            if (!hasExternalStoragePublicPicture(imageName)) {
                isImage = false;
                new DownloadImageTask().execute(ImageLinkURL);
                Log.v("log_tag", "if");
                isImage = true;
                File sdImageMainDirectory = new File(Environment
                        .getExternalStorageDirectory(), getResources()
                        .getString(R.string.directory));
                sdImageMainDirectory.mkdirs();
                File file = new File(sdImageMainDirectory, imageName);
                Log.v("log_tag", "Directory created");
            }

        } catch (MalformedURLException e) {
            Log.v(TAG, e.toString());
        }
        return ("/sdcard/Hanud/”+imageName+".jpg");

    }


    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();
    }

1 个答案:

答案 0 :(得分:0)

我已经对你的案子进行了测试。我的例子非常简单,我在舞台上放了一个按钮。当我点击按钮时,我将启动两个asynctask来下载两张图片。我在我的SD卡中创建了一个文件夹。经过测试,我可以在文件夹中找到两张图片。

检查完代码后,我猜你有一个类变量 ImageLink ,当你两次调用 getLocalLink 时会分配两次。因此,图像将存储在您的第二个图像名称文件中。

您可以查看我的示例,它适合您的要求。您可以创建多个asyncTask来下载多个图像。请检查AsyncTask部分。

http://jmsliu.com/1929/android-progress-dialog-example.html