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

How to create Image File inside Internal Cache Directory in Android

我想在 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 的目录。请帮忙,我是初学者。

试试这个:

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

我是这样实现的...

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