如何在Android中的内部缓存目录中创建图像文件

时间:2017-01-19 04:18:22

标签: android android-file

我希望在Android内部存储中的cache / images /中有image.png。

我无法使用以下代码:

File directory = new File(getContext().getCacheDir(), "images");
directory.mkdirs();


File mypath=new File(directory,"image.png");

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(mypath);

    bmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}       

使用上面的代码我甚至无法创建名为images的目录。请帮助,我是初学者。

2 个答案:

答案 0 :(得分:2)

试试这个:

File sd = getCacheDir();
            File folder = new File(sd, "/myfolder/");
            if (!folder.exists()) {
                if (!folder.mkdir()) {
                    Log.e("ERROR", "Cannot create a directory!");
                } else {
                    folder.mkdirs();
                }
            }

            File fileName = new File(folder,"mypic.jpg");

            try {
                        FileOutputStream outputStream = new FileOutputStream(String.valueOf(fileName));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                        outputStream.close();

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

答案 1 :(得分:0)

我是这样实现的...

//create file
File file = new File(context.getExternalCacheDir(), System.currentTimeMillis() + ".png");

//draw image if created successfully
if (file.createNewFile()) {

//initialize image BitMap
Bitmap bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);

//initialize canvas and paint object
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);

//design part goes here using Paint and Canvas
...

//get file output stream and draw design on image file
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}