android实现拍照及获取照片上传至接口

这篇博客详细介绍了在Android应用中如何实现拍照、从相册选择图片,并进行图片上传的功能。开发者通过注册ActivityResultLauncher处理权限请求和图片选取结果,使用Camera和Intent交互,以及OkHttp进行文件上传。同时,代码中涉及到版本适配和文件存储路径的处理。
摘要由CSDN通过智能技术生成

o

由于一些方法的弃用及版本权限的限制,被坑了好多错误。主要是Activity的区别。
布局展示:
在这里插入图片描述
Activity代码:

package tian.project.easytostop.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import tian.project.easytostop.MainActivity;
import tian.project.easytostop.R;

/**
 * @author tian
 * @date 2022.6.17
 * @describe 拍照页面添加停车位的弹框显示活动
 *
 */
public class DialogActivity extends AppCompatActivity {
    private Integer choose=-1;
    //拍照
    private static final int TAKE_PHOTO = 1;
    //获取相册的图片
    private static final int CHOOSE_PHOTO = 2;
    private static final int ERROR_EXIT = -1;
    //uri对象
    private Uri imageUri;
    //获取照片
    private String imagePath = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //开启相机权限
        ActivityCompat.requestPermissions(
                DialogActivity.this,
                new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                },
                1);
        //需要回调时访问事件的方法-registerForActivityResult必须在生命周期STARTED之前调用
        ActivityResultLauncher<Intent> intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    System.out.println("回调数据" + result);
                    //响应码
                    int resultCode = result.getResultCode();
                    System.out.println("选择码" + choose);
                    //判断是否为拍摄图片
                    if (resultCode == RESULT_OK) {
                        switch (choose) {
                            case TAKE_PHOTO: {
                                //已拍摄
                                System.out.println("已拍摄!");
                                //上传照片
                                upload();
                                break;
                            }
                            case CHOOSE_PHOTO: {
                                //获取相册
                                System.out.println("已获取到照片!");
                                // 判断手机系统版本号
                                int version = Build.VERSION.SDK_INT;
                                System.out.println("判断手机系统版本号" + version);
                                File outputImage;
                                try {
                                    //                // 创建File对象,用于存储拍照后的图片
                                    outputImage = new File(getExternalCacheDir(), "output_image.jpg");
                                    System.out.println("------------------------01" + getExternalCacheDir());
                                    try {
                                        if (outputImage.exists()) {
                                            outputImage.delete();
                                        }
                                        outputImage.createNewFile();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    Uri uri = result.getData().getData();
                                    Bitmap imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
                                    System.out.println("获取imageBitmap"+imageBitmap);
                                    FileOutputStream fileOutputStream=new FileOutputStream(outputImage);
                                    imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                                    fileOutputStream.flush();
                                    fileOutputStream.close();
                                    Log.e("saveBitMap", "saveBitmap: 图片保存到" + getExternalCacheDir() +"/output_image.jpg");
                                    System.out.println("获取到相册后的图片路径为:"+imagePath);
                                    upload();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
//
                                break;
                            }
                            case ERROR_EXIT: {
                                break;
                            }
                        }
                        //判断是否为选择图片
                    }
                });
//        showBottomDialog();
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog, null);
        dialog.setContentView(view);

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
        dialog.findViewById(R.id.tv_take_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("DialogActivity", "onCreate:  实现拍摄!");
                dialog.dismiss();
                System.out.println("实现拍照的照片!");
//                // 创建File对象,用于存储拍照后的图片
                File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
                System.out.println("------------------------01" + getExternalCacheDir());
                try {
                    if (outputImage.exists()) {
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("SDK版本:" + Build.VERSION.SDK_INT);
                if (Build.VERSION.SDK_INT < 24) {
                    imageUri = Uri.fromFile(outputImage);
                } else {
                    imageUri = FileProvider.getUriForFile(DialogActivity.this, "tian.project.easytostop.fileprovider", outputImage);
                }
//                // 启动相机程序
                System.out.println("获取照片路径:" + imageUri);
                System.out.println("获取照片路径:" + imageUri.getPath());
//                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                startActivity(intent);
//                //需要回调时访问事件的方法-registerForActivityResult必须在生命周期STARTED之前调用
//                registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
//                        result -> {
//                            Intent data=result.getData();
//                            System.out.println("回调数据"+data);
//
//                        })
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE")
                        .putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                choose=TAKE_PHOTO;
                intentActivityResultLauncher.launch( intent);

            }
        });

        dialog.findViewById(R.id.tv_take_pic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("DialogActivity", "onCreate: 获取相册!");
                dialog.dismiss();
                if (ContextCompat.checkSelfPermission(DialogActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(DialogActivity.this, new String[]{ Manifest.permission. WRITE_EXTERNAL_STORAGE }, 1);
                } else {
                    //打开相册
                    System.out.println("打开相册");
                    Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    choose=CHOOSE_PHOTO;
                    intentActivityResultLauncher.launch(intent);
                }
            }
        });

        dialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("DialogActivity", "onCreate:取消操作!");
                dialog.dismiss();
                Intent intent=new Intent(DialogActivity.this, MainActivity.class)
                        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }
    /**
     * 上传照片
     */
    public void upload() {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                if(choose==TAKE_PHOTO){
                    imagePath="/storage/emulated/0/Android/data/tian.project.easytostop/cache/output_image.jpg";
//                }
                Log.d("DialogActivity", "upload-run: 上传照片!");
//                File file = new File("/storage/emulated/0/Android/data/tian.project.takepictures/cache/output_image.jpg");
                File file=new File(imagePath);
                System.out.println("测试返回结果imagePath:"+imagePath);
                MediaType mediaType=MediaType.Companion.parse("text/x-markdown; charset=utf-8");
                OkHttpClient okHttpClient = new OkHttpClient();
                RequestBody fileBody=RequestBody.Companion.create(file,mediaType);
                RequestBody body = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file", file.getName(),fileBody)
                        .build();

                String url = "http://119.23.176.137:9000/easy_to_stop/uploadFile/uploadImage";
                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                System.out.println(request);
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println("上传失败!");
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
//                        Gson gson = new GsonBuilder().create();
//                        System.out.println(gson);
                        System.out.println("图片上传成功"+result);
                    }
                });
            }
        }).start();
    }
    /**
     * todo 压缩图片
     * @param origin
     * @param ratio
     * @return
     */
    public Bitmap scaleBitmap(Bitmap origin, float ratio) {
        if (origin == null) {
            return null;
        }
        int width = origin.getWidth();
        int height = origin.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(ratio, ratio);
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        return newBM;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锐行织梦者

谢谢您的支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值