簡體   English   中英

將位圖保存到 Android API 28 中的外部存儲導致 0 B 文件

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

我正在嘗試將位圖保存到外部存儲。 我使用了在android-save image into gallery 中找到的代碼。 但是,生成的文件大小為 0 B,但確實包含縮略圖。 我的代碼是:

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

與其保存為 JPEG,不如嘗試保存為 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();
}

在此處找到類似問題的答案

同樣如評論中所述,請檢查,您是否已獲得讀/寫訪問權限? 如果沒有,請參考下面的代碼。

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM