Android realizes the function of uploading pictures

  • 2021-12-19 06:41:40
  • OfStack

In this paper, we share the specific code of Android to realize the function of uploading pictures for your reference. The specific contents are as follows

Set the picture path returned by taking pictures


 /**
     *  Set the picture path returned by taking pictures 
     * @param image  Picture path 
     * @param i  Conventional value 
     */
    protected void image(String image, int i) {
        // Create file Object, which is used to store the photo after taking a picture, which is also the photo path after taking a picture successfully 
        outputImage = new File(getExternalCacheDir(),image);
        try {
            // Determine whether the file exists, deletes and does not exist 
            if (outputImage.exists()){
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // The camera takes a picture and returns to the picture path 
        Uri photoUri;
        // Judge the current Android Version 
        if(Build.VERSION.SDK_INT>=24){
            photoUri = FileProvider.getUriForFile(TextActivity.this," Package name .FileProvider",outputImage);
        }else {
            photoUri = Uri.fromFile(outputImage);
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(intent, i);
    }

Call the system camera to take a picture and accept the returned picture path


@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == IMAGE_Y) {
                getImageView(binding.imageY,"0");
            }
            if (requestCode == IMAGE_Q) {
                getImageView(binding.imageQ,"1");
            }
        }

    }

Upload pictures


 /**
     *  Upload pictures 
     * @param view  Picture display  view
     */
    protected void getImageView(@NotNull ImageView view, String type) {
        Bitmap photo = BitmapFactory.decodeFile(outputImage.getAbsolutePath());
        view.setImageBitmap(photo);
        int direction = 0;
        try {
            ExifInterface exif = new ExifInterface(String.valueOf(outputImage));
            direction = Integer.parseInt(exif.getAttribute(ExifInterface.TAG_ORIENTATION));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Matrix matrix = new Matrix();
        Uri uri = Uri.fromFile(outputImage);
        String f = uri.getPath();
        Bitmap b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);
        switch (direction) {
            case 1:
                Log.d(" Picture orientation "," Top, left (horizontal / Normal) ");
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);
                break;
            case 2:
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);
                Log.d(" Picture orientation "," Top, Right (Horizontal Mirror) ");
                break;
            case 3:
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),180);
                Log.d(" Picture orientation "," Bottom, right (rotate 180 ) ");
                break;
            case 4:
                matrix.postScale(1, -1);
                b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);
                Log.d(" Picture orientation "," Bottom, left (vertical mirror) ");
                break;
            case 5:
                matrix.postScale(-1, 1);
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),270);
                b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);
                Log.d(" Picture orientation "," Left, top (mirrored horizontally and rotated clockwise 270 ) ");
                break;
            case 6:
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),90);
                Log.d(" Picture orientation "," Right, top (rotate clockwise 90 ) ");
                break;
            case 7:
                matrix.postScale(-1, 1);
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),90);
                b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);
                Log.d(" Picture orientation "," Right, Bottom (Horizontal Mirror, Clockwise Rotation 90 Degree) ");
                break;
            case 8:
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),270);
                Log.d(" Picture orientation "," Left, bottom (rotate clockwise 270 ) ");
                break;
            default:
                break;
        }
        try {
            File files = new File(new URI(uri.toString()));
            saveBitmap(b,files);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        try {
            String file = uploadImage(networkApi.getFormal() + "setImage", uri.getPath(), code, userId);
            TextBase.FileInfo fileInfo = new TextBase.FileInfo();
            fileInfo.setFilePath(file);
            mFileInfos.add(fileInfo);
            model.load(file,type);
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }

 /**
     *  Upload pictures 
     * @param url  Upload interface path 
     * @param imagePath  Picture path 
     * @param code  Only 1 Identification 
     * @return  Path to the server picture 
     * @throws IOException
     * @throws JSONException
     */
    public static String uploadImage(String url, String imagePath, String code, String userId) throws IOException, JSONException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Log.d("imagePath", imagePath);
        File file = new File(imagePath);
        RequestBody image = RequestBody.create(MediaType.parse("image/jpg"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", imagePath, image)
                .addFormDataPart("fileOid", code)
                .addFormDataPart("userId", userId)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", Token )
                .post(requestBody)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        JSONObject jsonObject = new JSONObject(response.body().string());
        return jsonObject.optString("msg");
}

Other tool classes


/**
     *  Method of compressing pictures 
     * @param url
     * @param width
     * @param height
     * @return
 */
    public static Bitmap getBitmapFromUrl(String url, double width, double height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; //  This property is set 1 Be sure to set the value to false
        Bitmap bitmap = BitmapFactory.decodeFile(url);
        //  Prevent OOM Occurrence 
        options.inJustDecodeBounds = false;
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = 1;
        float scaleHeight = 1;
        //  Zoom to Fixed Width and Height 
        if(mWidth <= mHeight) {
            scaleWidth = (float) (width/mWidth);
            scaleHeight = (float) (height/mHeight);
        } else {
            scaleWidth = (float) (height/mWidth);
            scaleHeight = (float) (width/mHeight);
        }
        //  Zoom the picture to a fixed size 
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true);
        //  Remember to recycle when you run out 
        bitmap.recycle();
        return newBitmap;
    }

    /**
     * Android Save Bitmap To a file 
     * @param bitmap
     * @param file
     * @return
     */
    public static boolean saveBitmap(Bitmap bitmap, File file) {
        if (bitmap == null)
            return false;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     *  Rotate a picture 
     * @param bitmap  Picture 
     * @param rotate  Angle 
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
        if (bitmap == null)
            return null;

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Matrix mtx = new Matrix();
        mtx.postRotate(rotate);
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
    }

Related articles: