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
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command