如何在将视频上传到Firebase之前减小其大小? [英] How can I reduce size of a video before uploading it to firebase?
问题描述
我正在开发社交媒体应用程序,用户可以在其中上传视频和图像.因此,在将视频上传到Firebase之前,我想减小视频的大小,以便它们可以更快地加载到应用程序供稿中.
I am developing social media app, in which user can upload videos and images. So before uploading the video to the firebase I want to reduce the size of the video so they load faster in the app feed.
当前,我正在使用以下代码.谁能向我展示一种减小视频大小的方法,然后再将其上传到Firebase?
Currently I am using below code. Can anyone just show me a way to reduce size of video before uploading it to firebase?
if(videoUri != null){
final StorageReference filereference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(videoUri));
uploadTask = filereference.putFile(videoUri);
uploadTask.continueWithTask(new Continuation() {
@Override
public Object then(@NonNull Task task) throws Exception {
if(!task.isSuccessful()){
throw task.getException();
}
return filereference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if(task.isSuccessful()){
Uri downloadUri = task.getResult();
myUrl= downloadUri.toString();
Date todayDate = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String date = formatter.format(todayDate);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
String postid = reference.push().getKey();
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("postid", postid);
hashMap.put("type", "video");
hashMap.put("postimage", myUrl);
hashMap.put("description", description.getText().toString());
hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());
hashMap.put("date", date);
reference.child(postid).setValue(hashMap);
progressDialog.dismiss();
Intent intent = new Intent(PostVideoActivity.this , MainActivity.class);
ContextCompat.startForegroundService(PostVideoActivity.this , intent);
startActivity(intent);
finish();
}else{
Toast.makeText(PostVideoActivity.this , "Failed to post" , Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}else{
Toast.makeText(PostVideoActivity.this , "No video found" , Toast.LENGTH_SHORT).show();
}
推荐答案
这是解决方案,创建文件
Here is solution, Create a file
File file;
ProgressDialog dialogUpload;
创建异步任务以压缩视频大小
Create Async Task to compress Video size
public class VideoCompressAsyncTask extends AsyncTask<String, String, String> {
Context mContext;
public VideoCompressAsyncTask(Context context) {
mContext = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialogUpload = new ProgressDialog(getActivity());
dialogUpload.setCancelable(false);
dialogUpload.setMessage("Please wait until the video upload is complete");
dialogUpload.show();
}
@Override
protected String doInBackground(String... paths) {
String filePath = null;
try {
String path = paths[0];
String directoryPath = paths[1];
filePath = SiliCompressor.with(mContext).compressVideo(path, directoryPath);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return filePath;
}
@Override
protected void onPostExecute(String compressedFilePath) {
super.onPostExecute(compressedFilePath);
File imageFile = new File(compressedFilePath);
ByteArrayOutputStream byteBuffer;
float length = imageFile.length() / 1024f; // Size in KB
String value;
if (length >= 1024)
value = length / 1024f + " MB";
else
value = length + " KB";
String text = String.format(Locale.US, "%s\nName: %s\nSize: %s", getString(R.string.video_compression_complete), imageFile.getName(), value);
Log.e(TAG, "text: " + text);
Log.e(TAG, "imageFile.getName() : " + imageFile.getName());
Log.e(TAG, "Path 0 : " + compressedFilePath);
try {
File file = new File(compressedFilePath);
InputStream inputStream = null;//You can get an inputStream using any IO API
inputStream = new FileInputStream(file.getAbsolutePath());
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
VideoUri = Uri.fromFile(file);
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
output64.close();
ba1 = output.toString();
// Here video size is reduce and call your method to upload file on server
uploadVideoMethod();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在按钮上,单击如下所示的调用AsycTask
On button click call AsycTask like below
new VideoCompressAsyncTask(getActivity()).execute(file.getAbsolutePath(), file.getParent());
注意:您可能会从onActivityResult获取文件.
Note: you may get file from onActivityResult.
希望这会对您有所帮助.
Hope this will help you.
这篇关于如何在将视频上传到Firebase之前减小其大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!