摄影圈子 hqmana.com

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

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;
    }
}

版权声明
本文为[骑鱼~过海]所创,转载请带上原文链接,感谢
https://blog.csdn.net/tian208/article/details/125340626

Scroll to Top