广告
返回顶部
首页 > 资讯 > 移动开发 >Android使用相机实现拍照存储及展示功能详解
  • 661
分享到

Android使用相机实现拍照存储及展示功能详解

Android相机Android使用相机拍照Android使用相机存储 2023-01-04 18:01:30 661人浏览 薄情痞子
摘要

目录无图片处理款配置存储路径映射配置 fileprovider布局文件主代码文件无图片处理款 配置存储路径映射 新建文件:res/xml/files.xml 使用 paths 标签映

无图片处理款

配置存储路径映射

新建文件:res/xml/files.xml

使用 paths 标签映射一个存储路径,而 external-path 表示存储路径的根路径位于外部存储器内

name 自定义名称,可以随便写;

path 存储的文件夹,写一个小圆点表示直接使用根目录文件夹

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:Android="Http://schemas.android.com/apk/res/android">
    <external-path
        name="myphotos"
        path="." />
</paths>

配置 fileprovider

开启 androidmanifest.xml 文件,在 application 标签下添加一个 provider 标签

provider 标签的几个主要属性介绍:

  • android:name 固定的,使用 android 官方提供的 fileprovider
  • android:authorities 自己为该 provider 取的名字,建议格式:包名+fileprovider
  • android:exported 设置为 false 表示本应用的其他 activity 不可以调用该 fileprovider 获取的内容!
  • android:grantUriPermissions 设置为 true 表示允许 uri 读写权限(这个必须开启!)

meta-data 标签填入我们存储文件的映射 xml,就是上一节我们编写的文件

<application
        ...>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            ...
        </activity>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.zhiyiyi.login.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/files" />
        </provider>
    </application>

布局文件

非常简单,一个 imageview+imagebutton 即可

注意这里的 imagebutton 使用了 android 官方自带的图标,挺实用的,大家可以多试试

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/image"
            android:layout_width="200dp"
            android:layout_height="200dp" />
        <ImageButton
            android:id="@+id/imagebtn"
            android:layout_width="100dp"
            android:layout_height="60dp"
            android:src="@android:drawable/ic_menu_camera" />
    </LinearLayout>
</LinearLayout>

主代码文件

由于内容较为复杂,这里分层讲,最后贴出完整代码

首先全局定义三个延后初始化的变量

分别存储我们的图片 uri,以及两个组件

特别注意! photoUri 的类型是 Uri 而不是 URI,这俩玩意完全不一样,别看岔了!

class MainActivity : AppCompatActivity() {
    private lateinit var photoUri: Uri
    private lateinit var btn: ImageButton
    private lateinit var image: ImageView
    ...
}

之后就是按钮点击唤醒相机拍照,并存储相片展示到 imageview 的过程

具体过程请看详细注释

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    // 初始化两个组件
    btn = findViewById(R.id.imagebtn)
    image = findViewById(R.id.image)
    btn.setOnClickListener {
        // 新建一个文件,他的位置位于外存根目录下,且文件名为outputimage.jpg
        val file = File(getExternalFilesDir(null), "outputimage.jpg")
        // 为避免输出流错误,需要捕获错误
        try {
            file.createNewFile()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        // 使用FileProvider.getUriForFile获取相片存储的URI
        // 参数一:上下文
        // 参数二:我们之前在androidmanifest中注册provider时自定义的authorities
        // 参数三:欲转换成uri路径的文件
        photoUri = FileProvider.getUriForFile(
            this@MainActivity,
            "com.zhiyiyi.login.fileprovider",
            file
        )
        // 使用隐式intent唤醒相机
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // 传入photouri,以保证我们的照片存储到指定位置
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
        // 老样子,不解释
        startActivityForResult(intent, 1)
    }
}

onActivityResult 部分

内容很简单,即检测响应值并解码图片文件->显示图片

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        1 -> {
            if (resultCode == RESULT_OK) {
                try {
                    // 使用bitmap解码文件
                    val bitmap =
                        BitmapFactory.decodeStream(contentResolver.openInputStream(photoUri))
                    // 将图片展示在imageview上面
                    image.setImageBitmap(bitmap)
                } catch (e: FileNotFoundException) {
                    e.printStackTrace()
                }
            }
        }
    }
}

完整代码展示:

package com.zhiyiyi.login
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import android.widget.ImageButton
import android.widget.ImageView
import androidx.core.content.FileProvider
import com.zhiyiyi.login.databinding.ActivityMainBinding
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.net.URI
import Kotlin.math.log
class MainActivity : AppCompatActivity() {
    private lateinit var photoUri: Uri
    private lateinit var btn: ImageButton
    private lateinit var image: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn = findViewById(R.id.imagebtn)
        image = findViewById(R.id.image)
        btn.setOnClickListener {
            Log.d("fuck", "tnnd就是拍不了照")
            val file = File(getExternalFilesDir(null), "outputimage.jpg")
            Log.d("fuck", file.absolutePath)
            try {
                file.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            photoUri = FileProvider.getUriForFile(
                this@MainActivity,
                "com.zhiyiyi.login.fileprovider",
                file
            )
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
            startActivityForResult(intent, 1)
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            1 -> {
                if (resultCode == RESULT_OK) {
                    try {
                        val bitmap =
                            BitmapFactory.decodeStream(contentResolver.openInputStream(photoUri))
                        image.setImageBitmap(bitmap)
                    } catch (e: FileNotFoundException) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }
}

本 demo 不负责权限申请,且根据作者真机调试,直接开启相机并不需要请求任何权限,故再次做忽略处理

下一节讲讲述如何缩放以及调节图片分辨率以达到最佳效果

到此这篇关于Android使用相机实现拍照存储及展示功能详解的文章就介绍到这了,更多相关Android使用相机内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Android使用相机实现拍照存储及展示功能详解

本文链接: https://www.lsjlt.com/news/176734.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作