将位图保存到app文件夹

时间:2015-05-27 11:17:03

标签: android bitmap

当我的应用首次启动时,它会让用户选择个人资料照片。这可以在拍摄照片时完成,或者从画廊中选择。

用户获取图片后,必须将其保存在设备的内部存储空间中,并在应用中用作用户的个人资料图片。

此过程运行正常,用户获取图片,并在保存之前在imageview中显示。但是为了将图像保存在内部存储器中,我遇到了一些麻烦。我已经尝试了几种方法来做到这一点,而且大多数方法似乎都有效。但是当我尝试它们时,图片没有被保存,或者至少我找不到保存它的文件夹。

我试过这三种方式:

首先:

File directory = getDir("profile", Context.MODE_PRIVATE);
File mypath = new File(directory, "thumbnail.png");

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(mypath);
    mybitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.close();
} catch (Exception e) {
    e.printStackTrace();
}

第二

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
mybitmap.compress(Bitmap.CompressFormat.PNG, 90, bytes);

FileOutputStream fos = null;
try {
    fos = openFileOutput("thumbnail.png", Context.MODE_PRIVATE);
    fos.write(bytes.toByteArray());
    fos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

第三

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
mybitmap.compress(Bitmap.CompressFormat.PNG, 90, bytes);

File fileWithinMyDir = new File(getFilesDir(), "thumbnail.png");
try {
    FileOutputStream fos = new FileOutputStream(fileWithinMyDir);
    fos.write(bytes.toByteArray());
    fos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

通常,图像会保存在路径中:android/data/AppName/app_data/但是没有在那里创建文件夹。无论如何,我已经查看了其他文件夹,但没有。

修改 -

在第一种方法中,我发现这是一个例外:

E/SAVE_IMAGE﹕ /data/data/com.example.myapp/app_profile/thumbnail.png: open failed: EISDIR (Is a directory)
java.io.FileNotFoundException: /data/data/com.example.myapp/app_profile/thumbnail.png: open failed: EISDIR (Is a directory)
Caused by: libcore.io.ErrnoException: open failed: EISDIR (Is a directory)

5 个答案:

答案 0 :(得分:3)

在尝试了几件事之后,这最终对我起了作用:

ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("profile", Context.MODE_PRIVATE);
if (!directory.exists()) {
    directory.mkdir();
}
File mypath = new File(directory, "thumbnail.png");

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(mypath);
    resizedbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.close();
} catch (Exception e) {
    Log.e("SAVE_IMAGE", e.getMessage(), e);
}

基本上是检查目录(不是文件)是否存在,如果不存在,则使用mkdir()创建目录。

答案 1 :(得分:3)

您可以使用此imagesaver类将位图图像保存到您的app文件夹 图像保护程序类代码如下所示

public class ImageSaver {
private String directoryName = "images";
private String fileName = "image.png";
private Context context;
private File dir;
private boolean external=false;

public ImageSaver(Context context) {
    this.context = context;
}

public ImageSaver setFileName(String fileName) {
    this.fileName = fileName;
    return this;
}

public ImageSaver setExternal(boolean external) {
    this.external = external;
    return this;
}

public ImageSaver setDirectory(String directoryName) {
    this.directoryName = directoryName;
    return this;
}

public void save(Bitmap bitmapImage) {
    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(createFile());
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@NonNull
private File createFile() {
    File directory;
    if (external) {
        directory = getAlbumStorageDir(directoryName);
        if (!directory.exists()){
            directory.mkdir();
        }
    } else {
        directory = new File(context.getFilesDir()+"/"+directoryName);
        if (!directory.exists()){
            directory.mkdir();
        }
    }

    return new File(directory, fileName);
}

private File getAlbumStorageDir(String albumName) {
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName);
    if (!file.mkdirs()) {
        Log.e("ImageSaver", "Directory not created");
    }
    return file;
}

public static boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    return Environment.MEDIA_MOUNTED.equals(state);
}

public static boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    return Environment.MEDIA_MOUNTED.equals(state) ||
            Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}

public Bitmap load() {
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(createFile());
        return BitmapFactory.decodeStream(inputStream);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

public boolean deleteFile() {
    File file = createFile();
    return file.delete();
}

}

然后在您从服务器获取位图的活动中(通过使用Glide或Picasso,您可以使用任何方法) 您应该在致电setExternal

之前设置.setDirectory
Bitmap bitmap=........//bitmap from code
    new ImageSaver(this)
            .setFileName("filename.jpg")
             .setExternal(false)//image save in external directory or app folder default value is false
            .setDirectory("dir_name")
            .save(bitmap); //Bitmap from your code

答案 2 :(得分:1)

了解您的要求。下面粘贴我测试和工作的一些代码。基本上从相机获取图像并将其保存在应用程序存储中。请仔细阅读。希望这有帮助。欢呼..

//用于保存图片...

private String saveToInternalSorage(Bitmap bitmapImage) {
    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    // Create imageDir
    File mypath = new File(directory, "profile.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.PNG, 100, fos);
        fos.close();
        Editor editor = sharedpreferences.edit();
        editor.putString("saved", "na");
        editor.commit(); 

    } catch (Exception e) {
        e.printStackTrace();
    }
    return directory.getAbsolutePath();
}

// ..从存储中加载图片

private void loadImageFromStorage(String path) {

    try {
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File path1 = cw.getDir("imageDir", Context.MODE_PRIVATE);
        File f = new File(path1, "profile.jpg");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
        ImageView img = (ImageView) findViewById(R.id.viewImage);
        img.setImageBitmap(b);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

答案 3 :(得分:0)

好吧,如果文件夹不存在,你需要创建它。

尝试运行此代码,看看它是否解决了您的问题:

File parentDestination = saveFile.getParentFile();
    if (!parentDestination.exists()) {
        parentDestination.mkdirs(); //make all the directory structures needed
    }

答案 4 :(得分:0)

试试这个......

您应该使用Bitmap.compress()方法将Bitmap另存为文件。它将压缩(如果使用的格式允许)你的图片并将其推入OutputStream。

以下是通过getImageBitmap(myurl)获取的Bitmap实例的示例,该实例可以压缩为JPEG,压缩率为85%:<​​/ p>

String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "FitnessGirl"+Contador+".jpg"); // the File to save to
fOut = new FileOutputStream(file);

Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush();
fOut.close(); // do not forget to close the stream

MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());