摄影圈子 hqmana.com

Android can take photos and upload photos to the interface

o

Due to the abandonment of some methods and the limitation of version permissions , A lot of mistakes were made . Mainly Activity The difference between .
Layout display :
 Insert picture description here
Activity Code :

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  Add a pop-up box of parking space on the photo page to show the activity  * */
public class DialogActivity extends AppCompatActivity {
    
    private Integer choose=-1;
    // Taking pictures 
    private static final int TAKE_PHOTO = 1;
    // Get the picture of the album 
    private static final int CHOOSE_PHOTO = 2;
    private static final int ERROR_EXIT = -1;
    //uri object 
    private Uri imageUri;
    // Get photos 
    private String imagePath = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        // Turn on camera permissions 
        ActivityCompat.requestPermissions(
                DialogActivity.this,
                new String[]{
    Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                },
                1);
        // Methods to access events when a callback is required -registerForActivityResult Must be in the life cycle STARTED Previous call 
        ActivityResultLauncher<Intent> intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
    
                    System.out.println(" Callback data " + result);
                    // Response code 
                    int resultCode = result.getResultCode();
                    System.out.println(" Selection code " + choose);
                    // Determine whether to take pictures 
                    if (resultCode == RESULT_OK) {
    
                        switch (choose) {
    
                            case TAKE_PHOTO: {
    
                                // Photographed 
                                System.out.println(" Photographed !");
                                // Upload photos 
                                upload();
                                break;
                            }
                            case CHOOSE_PHOTO: {
    
                                // Get album 
                                System.out.println(" Got photos !");
                                //  Determine the mobile phone system version number 
                                int version = Build.VERSION.SDK_INT;
                                System.out.println(" Determine the mobile phone system version number " + version);
                                File outputImage;
                                try {
    
                                    // //  establish File object , Used to store pictures after taking pictures 
                                    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(" obtain imageBitmap"+imageBitmap);
                                    FileOutputStream fileOutputStream=new FileOutputStream(outputImage);
                                    imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                                    fileOutputStream.flush();
                                    fileOutputStream.close();
                                    Log.e("saveBitMap", "saveBitmap:  Save the picture to " + getExternalCacheDir() +"/output_image.jpg");
                                    System.out.println(" The picture path after getting the album is :"+imagePath);
                                    upload();
                                } catch (IOException e) {
    
                                    e.printStackTrace();
                                }
//
                                break;
                            }
                            case ERROR_EXIT: {
    
                                break;
                            }
                        }
                        // Determine whether to select a picture 
                    }
                });
// showBottomDialog();
        //1、 Use Dialog、 Set up style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、 Setting up layout 
        View view = View.inflate(this, R.layout.dialog, null);
        dialog.setContentView(view);

        Window window = dialog.getWindow();
        // Set the pop-up position 
        window.setGravity(Gravity.BOTTOM);
        // Set the pop-up animation 
        window.setWindowAnimations(R.style.main_menu_animStyle);
        // Set dialog size 
        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:  Realize shooting !");
                dialog.dismiss();
                System.out.println(" To take photos !");
// //  establish File object , Used to store pictures after taking pictures 
                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 edition :" + 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);
                }
// //  Start the camera program 
                System.out.println(" Get photo path :" + imageUri);
                System.out.println(" Get photo path :" + imageUri.getPath());
// Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
// startActivity(intent);
// // Methods to access events when a callback is required -registerForActivityResult Must be in the life cycle STARTED Previous call 
// registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
// result -> {
    
// Intent data=result.getData();
// System.out.println(" Callback data "+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:  Get album !");
                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 {
    
                    // Open album 
                    System.out.println(" Open album ");
                    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: Cancel operation !");
                dialog.dismiss();
                Intent intent=new Intent(DialogActivity.this, MainActivity.class)
                        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }
    /** *  Upload photos  */
    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:  Upload photos !");
// File file = new File("/storage/emulated/0/Android/data/tian.project.takepictures/cache/output_image.jpg");
                File file=new File(imagePath);
                System.out.println(" The test returns the result 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(" Upload failed !");
                    }
                    @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(" Image upload succeeded "+result);
                    }
                });
            }
        }).start();
    }
    /** * todo  The compressed image  * @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;
    }
}

版权声明
本文为[Ride a fish ~ cross the sea]所创,转载请带上原文链接,感谢
https://hqmana.com/2022/209/202207281544486229.html

Scroll to Top