Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ember.js/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重置/关闭应用程序后在Android上显示选定/存储的图像_Android_Image_Android Studio_Kotlin - Fatal编程技术网

重置/关闭应用程序后在Android上显示选定/存储的图像

重置/关闭应用程序后在Android上显示选定/存储的图像,android,image,android-studio,kotlin,Android,Image,Android Studio,Kotlin,我正在尝试显示用户通过相机或图像库选择的图像。即使在应用程序运行后,应用程序也应显示此图像 重新启动/终止并持续 我试图通过检查 onCreate(),如果有一个文件,应用程序可以在其中检查它是什么图像 需要显示,如果没有,则显示默认图像以指示配置文件 图片应由用户选择 MainActivity.kt package com.example.pickimagetakeexamples import android.annotation.SuppressLint import android.a

我正在尝试显示用户通过相机或图像库选择的图像。即使在应用程序运行后,应用程序也应显示此图像 重新启动/终止并持续

我试图通过检查
onCreate()
,如果有一个文件,应用程序可以在其中检查它是什么图像 需要显示,如果没有,则显示默认图像以指示配置文件 图片应由用户选择

MainActivity.kt

package com.example.pickimagetakeexamples

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.MediaScannerConnection
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import kotlinx.android.synthetic.main.activity_main.*
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*


class MainActivity : AppCompatActivity() {

    private var btn: Button? = null
    private var imageview: ImageView? = null
    private val GALLERY = 1
    private val CAMERA = 2

    @SuppressLint("SourceLockedOrientationActivity")
    override fun onCreate(savedInstanceState:Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

        btn = findViewById<View>(R.id.btn) as Button
        imageview = findViewById<View>(R.id.iv) as ImageView

        val wallpaperDirectory = File(getExternalFilesDir(null).toString() + IMAGE_DIRECTORY)

        if (!wallpaperDirectory.exists())
        {

        iv.setImageBitmap(BitmapFactory.decodeFile("/wallpaperDirectory"))

        } else {

            val img = BitmapFactory.decodeResource(resources, R.mipmap.profile_image)
            val round = RoundedBitmapDrawableFactory.create(resources, img)
            round.isCircular = true
            iv.setImageDrawable(round)
            println("Image_Directory")
            println(IMAGE_DIRECTORY)

        }

        btn!!.setOnClickListener { showPictureDialog() }

    }

    private fun showPictureDialog() {
        val pictureDialog = AlertDialog.Builder(this)
        pictureDialog.setTitle("Select Action")
        val pictureDialogItems = arrayOf("Select Photo From Gallery", "Capture Photo From Camera")
        pictureDialog.setItems(pictureDialogItems
        ) { dialog, which ->
            when (which) {
                0 -> choosePhotoFromGallary()
                1 -> takePhotoFromCamera()
            }
        }
        pictureDialog.show()
    }

    fun choosePhotoFromGallary() {
        val galleryIntent = Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI)

        startActivityForResult(galleryIntent, GALLERY)
    }

    fun takePhotoFromCamera() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, CAMERA)
    }

    public override fun onActivityResult(requestCode:Int, resultCode:Int, data: Intent?) {

        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == GALLERY)
        {
            if (data != null)
            {
                val contentURI = data.data
                try
                {
                    val bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, contentURI)
                    val round = RoundedBitmapDrawableFactory.create(resources, bitmap)
                    round.isCircular = true

                    val path = saveImage(bitmap)
                    Toast.makeText(this@MainActivity, "Image Saved!", Toast.LENGTH_SHORT).show()
                    imageview!!.setImageDrawable(round)

                }
                catch (e: IOException) {
                    e.printStackTrace()
                    Toast.makeText(this@MainActivity, "Failed!", Toast.LENGTH_SHORT).show()
                }
            }
        }
        else if (requestCode == CAMERA)
        {
            val thumbnail = data!!.extras!!.get("data") as Bitmap
            val round = RoundedBitmapDrawableFactory.create(resources, thumbnail)
            round.isCircular = true
            imageview!!.setImageDrawable(round)
            saveImage(thumbnail)
            Toast.makeText(this@MainActivity, "Image Saved!", Toast.LENGTH_SHORT).show()

            }
    }

    fun saveImage(myBitmap: Bitmap):String {
        val bytes = ByteArrayOutputStream()
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes)
        val wallpaperDirectory = File(getExternalFilesDir(null).toString() + IMAGE_DIRECTORY)
        println("WallpaperDirectory::" + wallpaperDirectory)

        // have the object build the directory structure, if needed.
        Log.d("fee",wallpaperDirectory.toString())
        if (!wallpaperDirectory.exists())
        {

            wallpaperDirectory.mkdirs()
        }

        try
        {
            Log.d("heel",wallpaperDirectory.toString())
            val f = File(wallpaperDirectory, ((Calendar.getInstance()
                    .getTimeInMillis()).toString() + ".jpg"))
            f.createNewFile()
            val fo = FileOutputStream(f)
            fo.write(bytes.toByteArray())
            MediaScannerConnection.scanFile(this,
                    arrayOf(f.getPath()),
                    arrayOf("image/jpeg"), null)
            fo.close()
            Log.d("TAG", "File Saved::--->" + f.getAbsolutePath())

            return f.getAbsolutePath()
        }
        catch (e1: IOException) {
            e1.printStackTrace()
        }

        return ""
    }

    companion object {
        private val IMAGE_DIRECTORY = "/demonuts"

    }
}
package com.example.pickimagetakeexamples
导入android.annotation.SuppressLint
导入android.app.AlertDialog
导入android.content.Intent
导入android.content.pm.ActivityInfo
导入android.graphics.Bitmap
导入android.graphics.BitmapFactory
导入android.media.MediaScannerConnection
导入android.os.Bundle
导入android.provider.MediaStore
导入android.util.Log
导入android.view.view
导入android.widget.Button
导入android.widget.ImageView
导入android.widget.Toast
导入androidx.appcompat.app.appcompat活动
导入androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
导入kotlinx.android.synthetic.main.activity\u main*
导入java.io.ByteArrayOutputStream
导入java.io.xml文件
导入java.io.FileOutputStream
导入java.io.IOException
导入java.util*
类MainActivity:AppCompatActivity(){
私有变量btn:按钮?=null
私有变量imageview:imageview?=null
私人画廊=1
私人摄像机=2
@SuppressLint(“源锁定定向活动”)
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
requestedOrientation=ActivityInfo.SCREEN\u方向\u肖像
btn=findViewById(R.id.btn)作为按钮
imageview=findViewById(R.id.iv)作为imageview
val wallperDirectory=File(getExternalFilesDir(null).toString()+IMAGE\u目录)
如果(!wallperDirectory.exists())
{
iv.setImageBitmap(BitmapFactory.decodeFile(“/wallperDirectory”))
}否则{
val img=BitmapFactory.decodeResource(资源,R.mipmap.profile\u图像)
val round=RoundedBitmapDrawableFactory.create(资源,img)
round.isCircular=true
iv.可设置图像绘制(圆形)
println(“图像目录”)
println(图像目录)
}
btn!!.setOnClickListener{showPictureDialog()}
}
私人娱乐节目图片目录(){
val pictureDialog=AlertDialog.Builder(此)
pictureDialog.setTitle(“选择操作”)
val pictureDialogItems=arrayOf(“从图库中选择照片”、“从相机捕获照片”)
pictureDialog.setItems(pictureDialogItems
){对话框,其中->
什么时候(哪个){
0->选择Romgallary()的照片
1->从照相机拍摄照片()
}
}
pictureDialog.show()
}
有趣的选择Romgallary的照片(){
val gallerycontent=Intent(Intent.ACTION\u PICK,
MediaStore.Images.Media.EXTERNAL\u CONTENT\u URI)
startActivityForResult(画廊内容、画廊)
}
从照相机()拍摄的有趣照片{
val intent=intent(MediaStore.ACTION\u IMAGE\u捕获)
startActivityForResult(意图、摄像机)
}
在ActivityResult上的公共覆盖乐趣(请求代码:Int,结果代码:Int,数据:Intent?){
super.onActivityResult(请求代码、结果代码、数据)
if(requestCode==GALLERY)
{
如果(数据!=null)
{
val contentURI=data.data
尝试
{
val bitmap=MediaStore.Images.Media.getBitmap(this.contentResolver,contentURI)
val round=RoundedBitmapDrawableFactory.create(资源,位图)
round.isCircular=true
val path=saveImage(位图)
Toast.makeText(this@MainActivity,“已保存图像!”,Toast.LENGTH\u SHORT.show()
imageview!!.setImageDrawable(圆形)
}
捕获(e:IOException){
e、 printStackTrace()
Toast.makeText(this@MainActivity,“失败!”,Toast.LENGTH\u SHORT.show()
}
}
}
else if(请求代码==摄像机)
{
val缩略图=数据!!.extras!!.get(“数据”)为位图
val round=RoundedBitmapDrawableFactory.create(参考资料,缩略图)
round.isCircular=true
imageview!!.setImageDrawable(圆形)
保存图像(缩略图)
Toast.makeText(this@MainActivity,“已保存图像!”,Toast.LENGTH\u SHORT.show()
}
}
趣味saveImage(myBitmap:Bitmap):字符串{
val bytes=ByteArrayOutputStream()
myBitmap.compress(Bitmap.CompressFormat.JPEG,90,字节)
val wallperDirectory=File(getExternalFilesDir(null).toString()+IMAGE\u目录)
println(“墙纸目录::”+墙纸目录)
//如果需要,让对象构建目录结构。
Log.d(“fee”,目录.toString())
如果(!wallperDirectory.exists())
{
wallperDirectory.mkdirs()
}
尝试
{
Log.d(“heel”,目录.toString())
val f=文件(目录,((Calendar.getInstance)()
.getTimeInMillis()).toString()+“.jpg”))
f、 createNewFile()
val fo=文件输出流(f)
fo.write(bytes.toByteArray())
MediaScannerConnection.scanFile(此,
arrayOf(f.getPath()),
arrayOf(“图像/jpeg”),空值)
fo.close()
Log.d(“标记”,“保存的文件::-->”+f.getAbsolutePath())
返回f.getAbsolutePath()
}
捕获(e1:IOException){
e1.printStackTrace()
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:exported="true"
    tools:context=".MainActivity">

    <!--        android:text="Select or Capture Image" -->
    <Button
        android:id="@+id/btn"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="40dp"
        android:width="2dp"
        android:background="#00000000" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="125dp"
        android:layout_height="125dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="-150dp"
        android:scaleType="fitXY"
        android:background="#00000000"
        android:src="@mipmap/profile_image" />


</LinearLayout>
val wallpaperDirectory = File(getExternalFilesDir(null).toString() + IMAGE_DIRECTORY)
wallpaperDirectory.deleteRecursively()
    val wallpaperDirectory = File(getExternalFilesDir(null).toString() + IMAGE_DIRECTORY)

    var listImages : Array<File>? = null
    listImages = wallpaperDirectory.listFiles()

    if(listImages != null && listImages.size!! > 0){
        iv.setImageBitmap(BitmapFactory.decodeFile(listImages[0].absolutePath))
    }
    else {
        val img = BitmapFactory.decodeResource(resources, R.drawable.profile_image)
        val round = RoundedBitmapDrawableFactory.create(resources, img)
        round.isCircular = true
        iv.setImageDrawable(round)
        println("Image_Directory")
        println(IMAGE_DIRECTORY)
    }