I am trying to compress the video but not able to compress fast way....using follow dependency also silicompressor /Video Compressor and Compressor..
The above list of compressor working fine but taking too much of time based on the video selection (For ex : if i select 2 MB video ~3 to 4 minute taking for compression)
class VideoCompressAsyncTask extends AsyncTask<String, String, String> {
Context mContext;
String path = File path;
File directory = new File(path);
public VideoCompressAsyncTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgress();
}
#Override
protected String doInBackground(String... paths) {
String filePath = null;
try {
filePath = SiliCompressor.with(mContext).compressVideo(myUrl, directory.getPath(), 0, 0, 0);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return filePath;
}
#Override
protected void onPostExecute(String compressedFilePath) {
super.onPostExecute(compressedFilePath);
File imageFile = new File(compressedFilePath);
}
}
Taking to much of time for video compression
Related
I have been compressing Images without any problems. Recently my app required video compress functionality to be added. Again, Silicompressor does the job but for some reason there is no audio in output file.
I am using code inside Runnable
private void compressVideo() {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
new CompressVideo().execute("false",uri.toString(),file.getPath());
// Uri muri = Uri.parse(uri.toString());
}
#SuppressLint("StaticFieldLeak")
private class CompressVideo extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... strings) {
String videoPath = null;
try {
Uri mUri = Uri.parse(strings[1]);
videoPath = SiliCompressor.with(PostReelActivity.this).compressVideo(mUri,strings[2]);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return videoPath;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
File file = new File(s);
Uri videoUri = Uri.fromFile(file);
uploadVideo(videoUri);
}
}
I have implemented the file upload to Amazon S3 following the Amazon guide and I have noticed that it is too slow. It takes around 10 sec to upload a simple png file around 20kb.
Initially I thought that the problem was related with threads and I have implemented an AsyncTask to upload the image, but the problem is still there. Following is the code employed to upload the image.
private class UploadFileTask extends AsyncTask<String, Integer, String> {
String remotePath;
String remoteFileName;
File file;
Context context;
S3UploadInterface listener;
public UploadFileTask(Context context,String remotePath,String remoteFileName, File file, S3UploadInterface listener){
this.context=context;
this.remotePath=remotePath;
this.remoteFileName=remoteFileName;
this.file=file;
this.listener=listener;
}
protected String doInBackground(String... params) {
credentialsProvider = new CognitoCachingCredentialsProvider(context,
"MY_PRIVATE_CREDENTIAL",
Regions.US_EAST_1);
TransferManager transferManager = new TransferManager(credentialsProvider);
Upload upload = transferManager.upload(remotePath, remoteFileName, file);
TransferProgress transferred = upload.getProgress();
while (!upload.isDone()) {
try {
publishProgress((int) transferred.getPercentTransferred());
} catch (Exception e) {
listener.uploadFailed(e);
}
}
return "uploaded";
}
protected void onProgressUpdate(Integer... progress) {
if (listener!=null)
listener.currentUploadProgress(progress[0]);
}
protected void onPostExecute(String result) {
if (listener!=null)
listener.uploadCompleted();
}
}
Any idea to solve this problem?
Thanks :)
This is going to hammer your CPU
while (!upload.isDone()) {
try {
publishProgress((int) transferred.getPercentTransferred());
} catch (Exception e) {
listener.uploadFailed(e);
}
}
Try adding Thread.sleep to give other threads time to run.
I am using Picasso for my image handling and use it to download images from a backend server and save to the local device. I use Target to save the image
Picasso.with(context)
.load(url)
.into(target);
Since the target code gets a bitmap, I have to use bitmap.compress() to write the image to local disk and I use JPEF format with quality of 100 assuming this will preserve the original quality.
Reading this it seems like this might not be what I want. In one case, the image on the backend was 90kb and the image that was written was 370kb. The original image can be generated using an arbitrary quality value. What is the easiest way to save the image using Picasso without the size/quality changing?
Target target = new Target() {
#Override
public void onPrepareLoad(Drawable arg0) {
}
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom arg1) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
FileOutputStream out = null;
try {
out = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void info) {
}
}.execute();
}
#Override
public void onBitmapFailed(Drawable arg0) {
}
};
UPDATE: more elegant solution here: https://github.com/square/picasso/issues/1025#issuecomment-102661647
Solved the problem using this solution.
In my PagerAdapter's instantiateItem() method, I run an AsyncTask that will download the image, save it to a file and then call Picasso with that image file.
PagerAdapter instantiateItem():
RemoteImageToImageViewAsyncTask remoteImageToImageViewAsyncTask =
new RemoteImageToImageViewAsyncTask(imageView, url, imagePath);
remoteImageToImageViewAsyncTask.execute();
RemoteImageToImageViewAsyncTask
public class RemoteImageToImageViewAsyncTask extends AsyncTask<Void, Void, Void> {
ImageView imageView;
String url;
File output;
public RemoteImageToImageViewAsyncTask(ImageView imageView, String url, File output) {
this.imageView = imageView;
this.url = url;
this.output = output;
}
#Override
protected Void doInBackground(Void... params) {
// Downloads the image from url to output
ImageDownloader.download(url, output);
return null;
}
#Override
protected void onPostExecute(Void params) {
Picasso.with(context)
.load(output)
.into(imageView);
}
}
I'm currently downloading and save some pictures in my Android app.
Here is the class which do the work :
public class BitmapPersist extends AsyncTask<String, Void, Boolean> {
private ArrayList<String> photosNotDownloaded;
private File pointDir;
private KickstartrGeolocPoint point;
private OnBitmapPersistedListener onBitmapPersistedListener;
public BitmapPersist(ArrayList<String> photosNotDownloaded, File pointDir, KickstartrGeolocPoint point, OnBitmapPersistedListener onBitmapPersistedListener) {
this.photosNotDownloaded=photosNotDownloaded;
this.pointDir=pointDir;
this.point=point;
this.onBitmapPersistedListener=onBitmapPersistedListener;
}
#Override
protected Boolean doInBackground(String... params) {
Bitmap bmp;
FileOutputStream out = null;
for(String url : photosNotDownloaded) {
//download the picture synchronously
bmp = ImageLoader.getInstance().loadImageSync(url);
try {
out = new FileOutputStream(pointDir.getPath() + File.separator + FileUtils.getPointPhotoPrefix(point) + FileUtils.getFileNameFromUrl(url));
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Throwable ignore) {
}
}
//send notification to the UI in order to scan again the directory and update the carousel
publishProgress();
}
return true;
}
#Override
protected void onPostExecute(Boolean success) {
if (success)
onBitmapPersistedListener.persistedSuccessfully(this.point, this.pointDir);
else
onBitmapPersistedListener.errorInPersistance();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
onBitmapPersistedListener.onProgress();
}
}
This class take an ArrayList of urls in parameter, and for each photo, it download it and save it.
Each time a photo is persisted, a notification is sent to the view to update a carousel (thanks to publishProgress(); )
The problem is that publishProgress() does not work, and every photos are displayed at the same time when every photos are downloaded.
Here is the call of my asynctask :
private void persistImageforPoint(ArrayList<String> photosNotDownloaded, KickstartrGeolocPoint point, File pointDir) {
// Create a subfolder for each point with its id
if (!pointDir.exists()) {
if (!pointDir.mkdirs()) {
LogWrapper.debug(FileUtils.class, "Failed to create directory");
return;
}
}
//save the file. Asynchronous task --> do not block the UI
new BitmapPersist(photosNotDownloaded, pointDir, point, new OnBitmapPersistedListener() {
#Override
public void persistedSuccessfully(KickstartrGeolocPoint point, File pointDir) {
if(currentPoint!=null) {
File pointDirectory = FileUtils.getPointPhotoDir(getActivity(), currentPoint);
loadCarousel(currentPoint, pointDirectory);
}
}
#Override
public void errorInPersistance() {
LogWrapper.error(getClass(),"Error persisting image");
}
#Override
public void onProgress() {
if(currentPoint!=null) {
final File pointDir = FileUtils.getPointPhotoDir(getActivity(), currentPoint);
loadCarousel(currentPoint, pointDir);
}
}
}).execute();
}
I don't have any errors in my logcat.
Thanks for your help ;)
I have two AsyncTasks, one is used to download xml file (DownloadTask), another is for parsing the file (ParseXMLTask).
There are two cases of using this tasks:
1) File doesn't exists > execute DownloadTask, onPostExecute > ParseXMLTask
2) File exists > execute only ParseXMLTask.
Everything is working, but the thing is, while performing the second case, there is a blocking the ui about 3 sec (black screen) that surely would make a user annoyed. This is absolutely confusing me, because the job in the second case seems to be easier.
So when I am testing my app, a situation is like that: I click on the button for the first time, file is being downloaded, saved on the sd card, parsed and finally opened. Then I go back and click on the button again. Now I see that lag while switching between activities.
Code:
Executing the tasks
private void downloadPack() {
if (packDownloaded) {
parseXML();
} else {
download = new DownloadFile(fileName, this, loadingBar);
download.execute(serverURL + fileName + ".xml");
}
}
private void parseXML() {
ParseXMLTask parseTask = new ParseXMLTask(this, this);
parseTask.execute(PATH + fileName + ".xml");
}
public void postDownload(File result) {
parseXML();
}
public void postParse() {
Intent packIntent = new Intent(this, PackActivity.class);
startActivity(packIntent);
}
ParseXMLTask.java
public class ParseXMLTask extends AsyncTask<String, Integer, Void> {
private Context context;
private XmlPullParser xpp;
private IPostParse iPostParse;
public ParseXMLTask(Context context, IPostParse iPostParse) {
this.context = context;
this.iPostParse = iPostParse;
}
#Override
protected Void doInBackground(String... params) {
File file = new File(params[0]);
/* doing the job */
}
#Override
protected void onPostExecute(Intent result) {
iPostParse.postParse(result);
}
}
DownloadFile.java
public class DownloadFile extends AsyncTask<String, Integer, File> {
private static final String PATH = Environment
.getExternalStorageDirectory().getPath() + "/.chgkgame/";;
private File dir;
private ProgressBar progressBar;
private String fileName;
private IPostDownload postDownload;
private boolean download;
public DownloadFile(String name, IPostDownload pDownload, ProgressBar pBar) {
progressBar = pBar;
fileName = name;
postDownload = pDownload;
}
#Override
protected File doInBackground(String... sUrl) {
URL url;
try {
url = new URL(sUrl[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileLength = urlConnection.getContentLength();
dir = new File(PATH + fileName + ".xml");
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(dir);
byte[] data = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return dir;
}
#Override
protected void onPostExecute(File result) {
if (postDownload != null) postDownload.postDownload(result);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (progressBar != null) {
progressBar.setProgress(values[0]);
}
}
}
There is nothing wrong with the above.
The parsing is pretty fast that is why you only see the layout for a split second.
The black screen will be the PackActivity loading, check this activity for what is blocking the UI thread.
You could have also put LogCat messages in to show that the parsing has finished and onCreate of the next Activity is called.