继续学习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:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/takePhotpBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="照相"/>
    <Button
        android:id="@+id/fromAlbumBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="从相册选取"/>
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

</LinearLayout>
package com.example.cameraalbumtest

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.util.Base64
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import com.example.cameraalbumtest.util.Animal.animal1
import java.io.ByteArrayOutputStream
import java.io.File

class MainActivity : AppCompatActivity() {
    val takePhoto=1
    val fromAblum=2


    lateinit var imageUri: Uri
    lateinit var outputImage:File

    lateinit var takePhotoBtn:Button
    lateinit var fromAblumBtn:Button
    lateinit var imageView:ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        takePhotoBtn=findViewById<Button>(R.id.takePhotpBtn)
        imageView=findViewById<ImageView>(R.id.imageView)
        fromAblumBtn=findViewById(R.id.fromAlbumBtn)
        takePhotoBtn.setOnClickListener {
//            创建File对象,用于存储拍照后的照片
            outputImage=File(externalCacheDir,"output_image.jpg")
            if (outputImage.exists()){
                outputImage.delete()
            }
            outputImage.createNewFile()
            imageUri=if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) {
                FileProvider.getUriForFile(this,"com.example.cameraalbumtest.fileprovider",outputImage)
            }else{
                Uri.fromFile(outputImage)
            }

            //启动相机程序
            val intent=Intent("android.media.action.IMAGE_CAPTURE")
            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri)
            startActivityForResult(intent,takePhoto)
            Log.e("TAG", "onCreate: ${imageUri}" )
        }

        fromAblumBtn.setOnClickListener {
            //打开文件选择器
            val intent=Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            //指定只显示图片
            intent.type="image/*"
            startActivityForResult(intent,fromAblum)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode){
            takePhoto ->{
                if (resultCode == Activity.RESULT_OK){
                    //将拍摄照片显示出来
                    val bitmap=BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri))
                    Log.e("TAG", "sdf${bitmap}", )
                    imageView.setImageBitmap(rotateIfRequired(bitmap))

                    // 将Bitmap对象转换为字节数组
                    val baos = ByteArrayOutputStream()
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
                    val byteArray = baos.toByteArray()

                    // 将字节数组编码为Base64字符串
                    val base64Image = Base64.encodeToString(byteArray, Base64.DEFAULT)
//                    Log.e("okok", "Base64 Image: ${base64Image}")
                    Thread {
                        // 在子线程中调用 animal1 函数执行网络请求
                        val result = animal1(base64Image) // 传入你需要的参数,比如图片的 Base64 编码字符串

                        // 网络操作完成后,如果需要更新UI,需要回到主线程
                        runOnUiThread {
                            // 在主线程中更新UI
                            // 这里只是一个简单的示例,你可以根据你的实际需求更新UI
                            // 例如更新UI控件状态或者显示网络请求结果
                            if (result != null) {
                                Log.e("dhioas", "okokkokokokokok: ${result}", )
                                // 处理网络请求结果
                                // 例如解析 JSON,展示识别结果等
                            } else {
                                // 处理网络请求失败的情况
                            }
                        }
                    }.start()
                }
            }

            fromAblum->{
                if (resultCode==Activity.RESULT_OK&&data!=null){
                    // 获取选择的图片的URI
                    val selectedImageUri = data.data
                    // 将选择的图片转换为Base64编码
//                    //将选择的图片显示
//                    data.data?.let { uri->
//                        val bitmap=getBitmapFromUri(uri)
//                        imageView.setImageBitmap(bitmap)
//                    }
                    val base64Image = selectedImageUri?.let { uri ->
                        val bitmap = getBitmapFromUri(uri)
                        bitmap?.let { bmp ->
                            // 将Bitmap对象转换为字节数组
                            val baos = ByteArrayOutputStream()
                            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos)
                            val byteArray = baos.toByteArray()
                            // 将字节数组编码为Base64字符串
                            Base64.encodeToString(byteArray, Base64.DEFAULT)
                        }
                    }
                    data.data?.let {uri ->
                        val bitmap=getBitmapFromUri(uri)
                        imageView.setImageBitmap(bitmap)
                    }
                    base64Image?.let {
                        Thread {
                            // 在子线程中调用 animal1 函数执行网络请求
                            val result = animal1(base64Image) // 传入你需要的参数,比如图片的 Base64 编码字符串

                            // 网络操作完成后,如果需要更新UI,需要回到主线程
                            runOnUiThread {
                                // 在主线程中更新UI
                                // 这里只是一个简单的示例,你可以根据你的实际需求更新UI
                                // 例如更新UI控件状态或者显示网络请求结果
                                if (result != null) {
                                    Log.e("dhioas", "okokkokokokokok: ${result}", )
                                    // 处理网络请求结果
                                    // 例如解析 JSON,展示识别结果等
                                } else {
                                    // 处理网络请求失败的情况
                                }
                            }
                        }.start()
                    }

                }
            }
        }
    }

    private fun getBitmapFromUri(uri: Uri) =contentResolver.openFileDescriptor(uri,"r")?.use {
        BitmapFactory.decodeFileDescriptor(it.fileDescriptor)
    }



    private fun rotateIfRequired(bitmap: Bitmap?): Bitmap? {
        val exif=ExifInterface(outputImage.path)
        val orientation=exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
            ExifInterface.ORIENTATION_NORMAL)
        return when(orientation) {
            ExifInterface.ORIENTATION_ROTATE_90->rotateBitmap(bitmap,90)
            ExifInterface.ORIENTATION_ROTATE_180->rotateBitmap(bitmap,180)
            ExifInterface.ORIENTATION_ROTATE_270->rotateBitmap(bitmap,270)
            else ->bitmap
        }
    }

    private fun rotateBitmap(bitmap: Bitmap?, degree: Int): Bitmap? {

        val matrix=Matrix()
        matrix.postRotate(degree.toFloat())
        val rotatedBitmap=
            bitmap?.let { Bitmap.createBitmap(it,0,0,bitmap.width,bitmap.height,matrix,true) }
        if (bitmap != null) {
            bitmap.recycle()
        }

        return rotatedBitmap;
    }
}

 

posted on 2024-03-26 21:49  许七安gyg  阅读(2)  评论(0编辑  收藏  举报
$(document).ready(function() { // 禁止右键 $(document).bind("contextmenu", function(){return false;}); // 禁止选择 $(document).bind("selectstart", function(){return false;}); // 禁止Ctrl+C 和Ctrl+A $(document).keydown(function(event) { if ((event.ctrlKey&&event.which==67) || (event.ctrlKey&&event.which==86)) { //alert("对不起,版权所有,禁止复制"); return false; } }); });