简体   繁体   中英

Saving Bitmap to External Storage in Android API 28 Result in 0 B file

I'm trying to save a bitmap to external storage. I have used the code that I have found in android - save image into gallery . However, the resulting file is 0 B in size but do contain thumbnail. My code is:

private fun saveBitmap(bitmap: Bitmap, name: String) {
    val contentValues = contentValuesOf(
        MediaStore.MediaColumns.TITLE to name,
        MediaStore.MediaColumns.DISPLAY_NAME to name,
        MediaStore.MediaColumns.MIME_TYPE to "images/jpeg",
        MediaStore.MediaColumns.DATE_ADDED to System.currentTimeMillis()
    )

    val resolver = contentResolver
    val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
    val outputStream = resolver.openOutputStream(uri!!)!!
    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream)
    outputStream.flush()
    outputStream.close()
}

Rather than saving to JPEG try saving as PNG

try (FileOutputStream out = new FileOutputStream(filename)) {
    bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
    // PNG is a lossless format, the compression factor (100) is ignored
} catch (IOException e) {
    e.printStackTrace();
}

Please find similar question answered here

Also as mention in comment please check, have you taken permission for read/write access? If not then please refer the below code.

if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
//File write logic here
return true;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM