Android - 通过AsyncTask将图像保存到SD卡失败

时间:2017-03-12 08:17:27

标签: android android-asynctask android-bitmap

我的drawables文件夹中有图像。活动打开它们,我选择所需的图像并单击按钮。它们必须通过扩展ImageSavingTask的{​​{1}}类实例执行保存在我的SD卡上。

Here's what my MainActivity looks like.

这是我的AsyncTask代码:

onClick

然后用@Override public void onClick(View v) { for (int i = 0; i < 26; i++) if (checkBoxes[i].isChecked()) { imageIndex = new ImageIndex(); //ImageIndex-a class with single index field which reserves the checked checkbox indexes. imageIndex.index = i; Bitmap bitmap = ((BitmapDrawable) (images[i].getDrawable())).getBitmap(); SaveImageTask saveImageTask = new SaveImageTask(); saveImageTask.execute(bitmap); //The class SaveImageTask extends AsyncTask<Bitmap, Void, Void> } } 方法处理所选图像。

doInBackground

我的清单中添加了 @Override protected Void doInBackground(Bitmap... params) { FileOutputStream outStream = null; try { Bitmap bitmap = params[0]; ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] imageBytes = stream.toByteArray(); File sdCard = Environment.getExternalStorageDirectory(); Drawable drawable = new BitmapDrawable(getResources(), bitmap); File dir = new File(sdCard.getAbsolutePath()); dir.mkdirs(); String fileName = "Saved image " + imageIndex.index; //The reserved index of checkbox creates a name for the new file. File outFile = new File(dir, fileName); outStream = new FileOutputStream(outFile); outStream.write(imageBytes); outStream.flush(); outStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } 行。

将USB连接到手机后,没有发生错误,但没有图像保存到我的SD卡。我无法使用Windows搜索在手机上找到图像。调试没有给出任何答案。这可能是什么问题?

No errors on debug

3 个答案:

答案 0 :(得分:0)

您似乎没有要求在SD卡上写入文件的运行时权限。从Android M及以上版本开始,您需要在运行时请求写入权限以将任何文件保存在外部SD卡上。

检查此链接,了解如何请求运行时权限 - https://developer.android.com/training/permissions/requesting.html

您也可以使用Google图书馆 - https://github.com/googlesamples/easypermissions 请求权限。

答案 1 :(得分:0)

我将所选索引添加到索引和位图的2个ArrayLists中。在doInBackground方法中,我创建了一个循环。

为了立即在卡片上显示图像,我使用了MediaScannerConnection.scanFile方法。

for (int i = 0; i < 26; i++)
    if (checkBoxes[i].isChecked()) {
        index.add(i);
        bitmap.add(bitmaps[i]);
    }
if (bitmap.size() > 0)
    new SaveImageTask().execute();

doInBackground方法:

protected Void doInBackground(Void... params) {
            for (int i = 0; i < bitmap.size(); i++) {
                try {
                    fname = "Saved image " + (index.get(i)) + ".jpg";
                    file = new File(myDir, fname);
                    if (file.exists()) file.delete();
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.get(i).compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                    MediaScannerConnection.
                            scanFile(getApplicationContext(), new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

我没有字段和参数就离开了ImageSavingTask

答案 2 :(得分:0)

我认为你尝试写字节的问题。

使用以下解决方案..

@Override
protected Void doInBackground(Bitmap... params) {
      Bitmap bitmap = params[0];
      saveToInternalStorage(bitmap, "MyImage"); // pass bitmap and ImageName
      return null;
}

//Method to save Image in InternalStorage
private void saveToInternalStorage(Bitmap bitmapImage, String imageName) {

            File mypath = new File(Environment.getExternalStorageDirectory(), imageName + ".jpg");

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(mypath);
                // Use the compress method on the BitMap object to write image to the OutputStream
                bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

注意:请确保您已添加存储读/写权限,并且不要忘记在Marshmallow及更高版本上获得许可。