current position:Home>Android short video development, call the camera and album, compress the pictures and upload them

Android short video development, call the camera and album, compress the pictures and upload them

2022-01-27 01:38:52 Cloudleopard network technology

android Short video development , Call camera 、 Photo album , Compress the picture and upload the relevant code
rewrite webChromeClient Of onShowFileChooser Method

 @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
    
            mUploadCallbackAboveL = filePathCallback;
            openAlbum();
            return true;
        }

fileChooserParams You can receive h5 in input Some parameters of the tag , After selecting the file , Will file uri Pass to filePathCallback.
Link to the original text : Call native camera 、 Photo album

Select call camera or album

private void openAlbum() {
    
        //  Set up the camera by specifying the storage location of the camera 
        String filePath = Environment.getExternalStorageDirectory() + File.separator
                + Environment.DIRECTORY_PICTURES + File.separator;
        String fileName = "IMG_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
        image = new File(filePath + fileName);
        imageUri = Uri.fromFile(image);
        Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        Intent Photo = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        Intent chooserIntent = Intent.createChooser(Photo, " Choose a picture ");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{
    captureIntent});
        startActivityForResult(chooserIntent, REQUEST_CODE);
    }

adopt imageUri Save the storage location of the photos taken by the camera . use Intent Open and select the camera 、 Of an album or folder activity.

Receive selected photos , Or take pictures back uri

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
    
           if (mUploadCallbackAboveL != null) {
    
                chooseAbove(resultCode, data);
            } else {
    
                Toast.makeText(this, " An error occurred ", Toast.LENGTH_SHORT).show();
            }
        }
    }

choosAbove Method to process the obtained uri, And send it back to filePathCallback.

Handle uri
Specific processing steps , adopt uri Get a picture of path, Read the picture , Compress the picture and store it again , The compressed picture uri Send back
(1). chooseAbove Method

private void chooseAbove(int resultCode, Intent data) {
    
        if (RESULT_OK == resultCode) {
    
            updatePhotos();
            if (data != null) {
    
//  Process selected photos 
                Uri[] results;
                Uri uriData = data.getData();
                if (uriData != null) {
    
                    results = new Uri[]{
    uriData};
                    try {
    
                        Uri compressImageUri = ImageCompressUtils.compressBmpFromBmp(uriToString(uriData));
                        mUploadCallbackAboveL.onReceiveValue(new Uri[]{
    compressImageUri});
                    } catch (Exception e) {
    
                        e.printStackTrace();
                        requestWritePermission();
                    }
                } else {
    
                    mUploadCallbackAboveL.onReceiveValue(null);
                }
            } else {
    
//  Process photos taken 
                try {
    
                    Uri compressImageUri = ImageCompressUtils.compressBmpFromBmp(imageUri.getPath());
                    mUploadCallbackAboveL.onReceiveValue(new Uri[]{
    compressImageUri});
                } catch (Exception e) {
    
                    e.printStackTrace();
                    requestWritePermission();
                }
            }
        } else {
    
            mUploadCallbackAboveL.onReceiveValue(null);
        }
        mUploadCallbackAboveL = null;
    }

Because the photos taken are stored in imageUri, Here, photos and album selection will be processed separately , Be careful , If no photo is selected , to filePathCallback Pass a null value , Prevent the upload from becoming invalid after only one click .

(2). Tools for compressing pictures ImageCompressUtils

Original link image compression tool class ( It solves the problem that the compressed picture is rotated )

public class ImageCompressUtils {
    
    /** * @param srcPath * @return * @description  When reading pictures from local to memory , That is, the picture from File The form becomes Bitmap form  *  characteristic : By setting the sampling rate , Reduce the pixels of the picture , To achieve in memory Bitmao Compress  *  Method statement :  The method is to Bitmap Compression of pictures in the form of ,  That is, by setting the sampling rate ,  Reduce Bitmap The pixel ,  This reduces the memory it occupies  */


    public static Uri compressBmpFromBmp(String srcPath) {
    
// String srcPathStr = srcPath;
        BitmapFactory.Options newOptions = new BitmapFactory.Options();
        newOptions.inJustDecodeBounds = true;// Read only edge , Don't read 
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOptions);

        newOptions.inJustDecodeBounds = false;
        int w = newOptions.outWidth;
        int h = newOptions.outHeight;
        float hh = 800f;
        float ww = 480f;
        int be = 1;
        if (w > h && w > ww) {
    
            be = (int) (newOptions.outWidth / ww);
        } else if (w < h && h > hh) {
    
            be = (int) (newOptions.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOptions.inSampleSize = be;// Set the sampling rate 
        newOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// This mode is the default , There is no 
        newOptions.inPurgeable = true;// At the same time, it will be effective 
        newOptions.inInputShareable = true;// When the system memory is insufficient, the picture will be automatically recycled 

        bitmap = BitmapFactory.decodeFile(srcPath, newOptions);
        int degree = readPictureDegree(srcPath);
        bitmap = rotateBitmap(bitmap, degree);
        return compressBmpToFile(bitmap);

    }


    /** * @param bmp * @description  Compress the picture when saving it locally ,  About to picture from Bitmap The form becomes File Compression in form , *  Characteristic is : File The pictures in the form are indeed compressed ,  But when you reread the compressed file by  Bitmap yes , The memory it occupies has not changed  *  The so-called mass compression , That is to change the bit depth of its image and the transparency of each pixel , in other words JPEG Compressed format , The transparent elements in the original picture will disappear , So this format is likely to cause distortion  */
    public static Uri compressBmpToFile(Bitmap bmp) {
    
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/shoppingMall/compressImgs/";

        File file = new File(path + System.currentTimeMillis() + ".jpg");
        // Determine whether the folder exists , If it does not exist, create a folder 
        if (!file.getParentFile().exists()) {
    
            file.getParentFile().mkdirs();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 80;
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        while (baos.toByteArray().length / 1024 > 100) {
    
            baos.reset();
            options -= 10;
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        try {
    
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
// copyExif(srcPathStr,file.getAbsolutePath());
// return file.getAbsolutePath();
            return Uri.fromFile(file);
        } catch (FileNotFoundException e) {
    
// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
    
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }


    /** *  Get the rotation angle of the picture  * * @param srcPath * @return */
    private static int readPictureDegree(String srcPath) {
    
        int degree = 0;
        try {
    
            ExifInterface exifInterface = new ExifInterface(srcPath);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
    
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
    
            e.printStackTrace();
        }
        return degree;
    }

    // Handle image rotation 
    private static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
    
        if (bitmap == null)
            return null;

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

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

}

Call the compression method , The compressed picture uri Pass to filePathCallback, End of upload .
That's all android Short video development , Call camera 、 Photo album , Compress the picture and upload the relevant code , More content welcome to follow the article

copyright notice
author[Cloudleopard network technology],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270138487193.html

Random recommended