Как отправить файл jpg в другой вид деятельности с намерением? в Android Kotlin? - PullRequest
0 голосов
/ 12 апреля 2020

У меня проблема, во-первых Как я могу отправить файл jpg другому занятию в Kotlin Android? Во-вторых, я делаю снимок из одного занятия и хочу показать это для просмотра изображения в другом упражнении !! Согласно моему исследованию. Я должен преобразовать это в Растровое изображение, если это правильно. Какой лучший способ сделать это?

Я хочу отправить этот jpg-файл с другим действием в webService ...

class ScanPlateActivity: AppCompatActivity () {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_scan_plate)
    home_toolbar_open_kit.setOnClickListener {  startActivity(Intent(this,MainActivity::class.java)) }



    viewFinder = findViewById(R.id.view_finder)


    // Request camera permissions
    if (allPermissionsGranted()) {
        viewFinder.post { startCamera() }
    } else {
        ActivityCompat.requestPermissions(
            this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
    }

    // Every time the provided texture view changes, recompute layout
    viewFinder.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
        updateTransform()
    }


}

private val executor = Executors.newSingleThreadExecutor()
private lateinit var viewFinder: TextureView

private fun startCamera() {
    // Create configuration object for the viewfinder use case
    val previewConfig = PreviewConfig.Builder().apply {
        setTargetResolution(Size(640,480))
    }.build()

    // Build the viewfinder use case
    val preview = Preview(previewConfig)

    // Every time the viewfinder is updated, recompute layout
    preview.setOnPreviewOutputUpdateListener {

        // To update the SurfaceTexture, we have to remove it and re-add it
        val parent = viewFinder.parent as ViewGroup
        parent.removeView(viewFinder)
        parent.addView(viewFinder, 0)

        viewFinder.surfaceTexture = it.surfaceTexture
        updateTransform()
    }
    val imageCaptureConfig = ImageCaptureConfig.Builder()
        .apply {
            // We don't set a resolution for image capture; instead, we
            // select a capture mode which will infer the appropriate
            // resolution based on aspect ration and requested mode
            setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
        }.build()

    // Build the image capture use case and attach button click listener
    val imageCapture = ImageCapture(imageCaptureConfig)
    capture_button.setOnClickListener {
        val intent =
            Intent(applicationContext, ImageServerActivity::class.java)


       file = File(
            externalMediaDirs.first(),
            "${System.currentTimeMillis()}.jpg"


        )

        imageCapture.takePicture(file, executor,
            object : ImageCapture.OnImageSavedListener {
                override fun onError(
                    imageCaptureError: ImageCapture.ImageCaptureError,
                    message: String,
                    exc: Throwable?
                ) {
                    val msg = "Photo capture failed: $message"
                    Log.e("CameraXApp", msg, exc)
                    viewFinder.post {
                        Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onImageSaved(file: File) {
                    val msg = "Photo capture succeeded: ${file.absolutePath}"
                    Log.d("CameraXApp", msg)
                    viewFinder.post {
                        Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                    }
                }
            })
        intent.putExtra("abs_path",file.absolutePath)
        intent.putExtra("path",file.toString())
        intent.putExtra("file", file)
        startActivity(intent)

    }
    // Bind use cases to lifecycle
    // If Android Studio complains about "this" being not a LifecycleOwner
    // try rebuilding the project or updating the appcompat dependency to
    // version 1.1.0 or higher.
    CameraX.bindToLifecycle(this, preview, imageCapture)

}

private fun updateTransform() {
    // TODO: Implement camera viewfinder transformations
}

/**
 * Process result from permission request dialog box, has the request
 * been granted? If yes, start Camera. Otherwise display a toast
 */
override fun onRequestPermissionsResult(
    requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
    if (requestCode == REQUEST_CODE_PERMISSIONS) {
        if (allPermissionsGranted()) {
            viewFinder.post { startCamera() }
        } else {
            Toast.makeText(this,
                "Permissions not granted by the user.",
                Toast.LENGTH_SHORT).show()
            finish()
        }
    }
}

/**
 * Check if all permission specified in the manifest have been granted
 */
private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
    ContextCompat.checkSelfPermission(
        baseContext, it) == PackageManager.PERMISSION_GRANTED
}

}

...