先来个简单的,使用 ImageView 把指定位置的图片显示出来.
然后会发现当要看一些较大的图片会失败.究其原因,是 android 的资源问题,太大太多的图片会内存溢出,而 ImageView 组件也有图片大小的要求.
此类较大的图片,可以采用压缩的方式显示在组件中,而不影响原图.这主要是 BitmapFactory.Options 的 inSampleSize 设置来实现的.
先构建界面,两个按钮一个图像显示组件
界面
<?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:orientation="vertical"
tools:context="com.cofox.functions.ViewChoseUploadFile.PhotoShow1Activity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/photo_show1_btnChoosePic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择图片路径" />
<Button
android:id="@+id/photo_show1_takePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="拍照并显示结果" />
</LinearLayout>
<ImageView
android:id="@+id/photo_show1_imgvwPicShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
由于指定要显示的图片文件是放在 sd 卡上的,所以需要申请一下权限.由于一会儿也要做拍照的工作,所以权限就把读和写的权限都申请下来.
打开 AndroidManifest.xml ,添加权限
然后打开代码编辑界面,在 onCreate 方法内添加 "选择图片路径" 按钮的操作
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
为什么要写两遍 options = BitmapFactory.Options() 呢?因为第一次是声明和初始化,而这个时候,options 还没有和任何图片文件产生关系,这时候 options 没什么作用.直到 bitmap = BitmapFactory.decodeFile(picFileName, options) 让它和一张图片有了联系,于是,再做图像文件的宽高取值就能够取得到了.
//选择图片路径
photo_show1_btnChoosePic.setOnClickListener {
val picFileName = "/sdcard/image.png"
if (!File(picFileName).exists()) {
Toast.makeText(this, "图片不存在", Toast.LENGTH_LONG).show()
return@setOnClickListener
}
val dm = DisplayMetrics() //获取手机分辨率
windowManager.defaultDisplay.getMetrics(dm)
var options = BitmapFactory.Options() //图像参数对象,为计算图像压缩比使用
options.inJustDecodeBounds = true
var bitmap = BitmapFactory.decodeFile(picFileName, options)
var num = CofoxBitmapInSampleSize(options, dm.widthPixels, dm.heightPixels)
options.inSampleSize = num
options.inJustDecodeBounds = false
bitmap = BitmapFactory.decodeFile(picFileName, options)
photo_show1_imgvwPicShow.setImageBitmap(bitmap)
}
显示指定图片文件
拍照并显示结果
拍照相对来说又要复杂一些.首先要调用相机拍照功能,设置好拍好的照片保存的位置和文件名称.而想要拍照之后,立刻欣赏刚刚的拍摄结果,需要覆写 onActivityResult 方法.显示图片的方法上边已经给出了没什么不一样.
而我们还有很大的一个步骤必须要做,在 android 系统升级到 7.0 版本以后,和以前的系统有很大的不同.它隐藏了文件的真实路径,暴出的路径是经过加工后的.这需要我们做一些更多的工作.
我们需要一个内容提供器,这需要在 AndroidManifest.xml 内进行注册
标签的内部使用来指定 Url 的共享路径,并引用了一个 @xml/file_paths 资源.这个资源现在还不存在,马上创建.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cofox.mykt.myweather">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.cofox.functions.ViewChoseUploadFile.PhotoShow1Activity" android:label="图片显示1"></activity>
<provider
android:authorities="com.cofox.functions.fileprovider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
右击 res 目录 ->New->Directory,创建一个 xml 目录;右击这个 xml 目录 ->New->File,创建 file_paths.xml 文件.然后修改 file-paths.xml 为下面代码:
这里的 extenal-path 是用来指定 Uri 共享的.path 属性的值就是表示共享的具体路径.当前为空的设置,表示将整个 SD 卡进行共享.
<?xml version="1.0" encoding="utf-8" ?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="" />
</PreferenceScreen>
最后一点要注意的,如果是古老的 android 4.4 之前的系统,访问 SD 卡的应用关联目录要声明权限.android 4.4 不需要声明.为了兼容那些老版本的系统,在 AndroidManifest.xml 中声明 SD 的访问权限.
在 onCreate 方法中添加按钮操作代码
在 AndroidManifest.xml 文件中配置的 android:authorities 属性的值必须和这里 FileProvider.getUrlFile() 方法中的第二个参数一致.
//拍照并显示结果
photo_show1_takePhoto.setOnClickListener {
picTakePhoto = Environment
.getExternalStorageDirectory().toString() + "/DCIM/Camera/Cofox" + getNow() + ".png"
var imageUri:Uri
//android 7.0版本以下的系统可以直接uri.fromFile取得真实图片路径,7.0及以上版本的系统,使用FileProvider封装过的Uri再提供出去.
if (Build.VERSION.SDK_INT >= 24){
imageUri = FileProvider.getUriForFile(this, "com.cofox.functions.fileprovider", File(picTakePhoto)) //需要手动添加AndroidManifest.xml的设置,以及xml路径和其内的文件和内容
}else{
imageUri = Uri.fromFile(File(picTakePhoto))
}
//启动相机拍照
intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(intent, 2)
}
覆写 onActivityResult 方法
拍照效果截图
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
2 -> {
if (resultCode == Activity.RESULT_OK) {
val dm = DisplayMetrics() //获取手机分辨率
windowManager.defaultDisplay.getMetrics(dm)
var options = BitmapFactory.Options() //图像参数对象,为计算图像压缩比使用
options.inJustDecodeBounds = true
var bitmap = BitmapFactory.decodeFile(picTakePhoto, options)
var num = CofoxBitmapInSampleSize(options, dm.widthPixels, dm.heightPixels)
options.inSampleSize = num
options.inJustDecodeBounds = false
bitmap = BitmapFactory.decodeFile(picTakePhoto, options)
photo_show1_imgvwPicShow.setImageBitmap(bitmap)
/*title =
" | " + num +
" | " + options.inSampleSize.toString() +
" | " + options.outWidth +
" | " + options.outHeight +
" | " + dm.widthPixels +
" | " + dm.heightPixels //picTakePhoto*/
}
}
}
}
/**
* Cofox 计算图片所需要的压缩比
* created at 2018/1/10 14:50
* 功能描述:
* 根据输入的参数宽高值,用option的宽高值做比较.如果option的任一值大于输入值,则进行2倍的压缩,然后再比较,如果压缩有的相应值仍大于输入值,则继续压缩,直到两个只都不大于为止,返回最终的inSampleSize值.
*
* 场景解释:图片如果太大的话,在android中有可能造成内存溢出而无法加载.另,ImageView对较大的图片也常常无法加载.因此需要设置inSampleSize.一般手机拍照的图片,在本手机上的inSampleSize为4就不影响图片显示质量.但是为了确定一个图片在加载前是否需要压缩,还是使用这个函数计算一下为好.
* 修改历史:
* file:cofoxFuction.kt
*
*
* 2018/1/10:
*
*/
fun CofoxBitmapInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int) : Int {
val width = options.outWidth //原文件宽度
val height = options.outHeight //原文件高度
var inSampleSize = 1
if ((width > reqWidth) || (height > reqHeight)) {
while (((width / inSampleSize) > reqWidth) || ((height / inSampleSize) > reqHeight)) {
inSampleSize++
// Log.d("CofoxFunc->", getNow()+ "|" +inSampleSize.toString())
}
}
Log.d("CofoxReturn->", getNow() + "|" + inSampleSize.toString() + "|" + width + "|" + height + "|" + reqWidth + "|" + reqHeight) return inSampleSize
}
来源: http://www.jianshu.com/p/fbd554b19b52