创建的ImageFile将作为0字节文件返回,如果保存到存储中也找不到

问题描述 投票:0回答:1

我正在尝试制作一个拍摄照片并将其上传到服务器的应用程序,它已经连接到服务器,但代码生成的图像始终为0字节,我尝试先将其保存到内部存储,然后上传但它仍然以 0 字节文件结尾,甚至在系统中找不到它。我将不胜感激任何帮助。

interface CameraResultHandler {
    fun handleCameraResult(requestCode: Int, resultCode: Int, data: Intent?)
}

class CameraHandler(private val activity: Activity): CameraResultHandler {
    lateinit var imageFile: File
    companion object {
        const val REQUEST_IMAGE_CAPTURE = 1
    }
    fun startCamera(){
        dispatchTakePicture()
        handleCameraResult(REQUEST_IMAGE_CAPTURE, RESULT_OK, null)
    }    
    fun dispatchTakePicture() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            val photoFile: File? = runBlocking {
                try {
                    createImageFile()
                } catch (ex: IOException) {
                    null
                }
            }
            photoFile?.also {
                imageFile = it
                takePictureIntent.resolveActivity(activity.packageManager)?.also {
                    activity.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
                }
            }
        }
    }
    override fun handleCameraResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            val progressDialog = ProgressDialog(activity).apply {
                setMessage("Uploading...")
                setCancelable(false)
                show()
            }
            CoroutineScope(Dispatchers.IO).launch {
                delay(5000) //ADDED A TIMER SO THAT UPLOAD IMAGE HAD TIME TO RUN, DIDN'T HELP
                uploadImage(imageFile) //UPLOADS THE FILE
                progressDialog.dismiss()
            }
        }
    }
@Throws(IOException::class)
    private fun createImageFile(): File {
        val imageFileName = "JPEG_" + System.currentTimeMillis() + "_"
        val storageDir = activity.getExternalFilesDir(null)
        val imageFile = File.createTempFile(
            imageFileName,
            ".jpg",
            storageDir
        )
        // Log the file path
        Log.d("CameraHandler", "File path: ${imageFile.absolutePath}")
        // Log the file size
        Log.d("CameraHandler", "File size: ${imageFile.length()} bytes")
        return imageFile
    }
}
java android kotlin camera
1个回答
0
投票

正如用户blackapps提到的,我不需要制作新函数,只需使用相机本身生成的Uri/Bitmap来处理文件并上传即可。谢谢blackapps,我希望你下次通勤时只开绿灯。

© www.soinside.com 2019 - 2024. All rights reserved.