The below code is working good, its generating image thumbnail for the video from the given url, but i want to know, is it possible to generate video thumbnail at suppose 100 milliseconds because by default its generating thumbnail at the beginning position so if in beginning the video screen is black then the thumbnail is also showing black so its looking quite odd. So is there any possibility to get the thumbnail by skipping some milliseconds.
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
String path;
public DownloadImage(ImageView bmImage, String path) {
this.bmImage = (ImageView ) bmImage;
this.path=path;
}
protected Bitmap doInBackground(String... urls) {
Bitmap myBitmap = null;
MediaMetadataRetriever mMRetriever = null;
try {
mMRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mMRetriever.setDataSource(path, new HashMap<String, String>());
else
mMRetriever.setDataSource(path);
myBitmap = mMRetriever.getFrameAtTime();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (mMRetriever != null) {
mMRetriever.release();
}
}
return myBitmap;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
You can use other overloaded methods of MediaMetadataRetriever to get frame of a particular time.
public Bitmap getFrameAtTime(long timeUs, int option) {
throw new RuntimeException("Stub!");
}
public Bitmap getFrameAtTime(long timeUs) {
throw new RuntimeException("Stub!");
}
public Bitmap getFrameAtTime() {
throw new RuntimeException("Stub!");
}
Related
So, I have this app that is connected to a WebService and I am already retrieving data from there, now I want to retrieve a image link and make that the imageView gets that image trough the link. Is that even possible? Appreciate any help :D
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
JSONArray paises = jsonObject.optJSONArray("paises");
if (paises != null) {
for (int j = 0; j < paises.length(); j++) {
JSONObject jsonObject1 = paises.getJSONObject(j);
System.out.println(jsonObject1.optString("Designacao"));
String K_PAIS = jsonObject1.getString("K_PAIS");
String Designacao = jsonObject1.getString("Designacao");
String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
String URL_IMAGEM = "http://something.something.pt" + URL_IMAGE_SMALL;
new DownloadImage(imageView6).execute(URL_IMAGEM);
HashMap<String, String> pais = new HashMap<>();
pais.put("K_PAIS", K_PAIS);
pais.put("Designacao", Designacao);
pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
pais.put("URL_IMAGEM", URL_IMAGEM);
listaPaises.add(pais);
}
}
System.out.println(jsonObject.optString("Designacao"));
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errpr!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
{...}
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (ImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
You can use Picasso, a wonderful image library.
Example:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Add dependency via Gradle:
compile 'com.squareup.picasso:picasso:2.5.2'
you can use any third party library
example use Glide library
this library will help you to fetch and display image on ImageView from url.
example:
Glide.with(context).load(image_url).into(your_image_view);
here is link for that library : https://github.com/bumptech/glide
You have to set your ImageView inside your XML as you normally do. Then you can use any third party library like Picasso or Glide that will load the image from the url and set it to your ImageView in your activity/fragment.
In your app build.gradle add
compile 'com.github.bumptech.glide:glide:3.7.0'
use this code to load image from url
Glide.with(getApplicationContext()).load("image_url").into(ImageView);
try this if you dont want to use third party library
new DownloadImage(imamgeview).execute(url);
create a Async Task
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
i hope you it will work in your case
step 1: create class named DownloadImage
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Step 2: execute AsyncTask
new DownloadImage(imgUserProfile).execute(userProfileUrl);
**Json Url like this: ** https://graph.facebook.com/1220130444748799/picture?height=400&width=400&migration_overrides=%7Boctober_2012%3Atrue%7D
I want to save imageView into sd card but I get the following exception (some times not always) when I try to get bitmap from imageView. Can somebody please help me? Thanks in advance
Caused by: java.lang.IllegalArgumentException: width and height must be > 0 at android.graphics.Bitmap.createBitmap(Bitmap.java:922)
public static class SaveImageToSD extends AsyncTask<String, Void, String> {
Context context;
ImageView mImageView;
ProgressDialog progressDialog;
public SaveImageToSD(Context context, ImageView iv, String name) {
this.context = context;
this.mImageView = iv;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", context.getResources().getString(R.string.please_wait), true);
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected String doInBackground(String... x) {
File projectFolder = new File(Environment.getExternalStorageDirectory() + File.separator + Settings.projectFolder + File.separator);
boolean folderCreateSuccess = true;
if (!projectFolder.exists()) {
folderCreateSuccess = projectFolder.mkdir();
}
if (folderCreateSuccess) {
Bitmap bitmap;
// Exception in if statement
if (mImageView.getDrawable() instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
} else {
Drawable d = mImageView.getDrawable();
bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
d.draw(canvas);
}
File image = new File(projectFolder, "GE_" + System.currentTimeMillis() + ".jpg");
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "title");
values.put(MediaStore.Images.Media.DESCRIPTION, "description");
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.ImageColumns.BUCKET_ID, image.toString().toLowerCase(Locale.US).hashCode());
values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, image.getName().toLowerCase(Locale.US));
values.put("_data", image.getAbsolutePath());
ContentResolver cr = context.getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
if (success) {
((ActionBarActivity)context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, context.getResources().getString(R.string.image_successfully_saved), Toast.LENGTH_SHORT).show();
}
});
} else {
((ActionBarActivity)context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, context.getResources().getString(R.string.image_successfully_saved), Toast.LENGTH_SHORT).show();
}
});
}
} else {
Log.i("Create Folder", "Error during create folder");
}
return "";
}
}
to set image I use following code, I'm using transparentDrawable because of Picasso wrap content problem
transparentDrawable.setBounds(new Rect(0, 0, 1000, 1000));
Picasso.with(mContext).load(((FBPhotoCard) mImageCards.get(position)).getThumbnail()).placeholder(transparentDrawable).noFade().into(holder.imageView);
I think the exception is of because d.getIntrinsicWidth(), d.getIntrinsicHeight() at line bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
According to Android docs drawable.getIntrinsicWidth() Return the intrinsic width of the underlying drawable object. Returns -1 if it has no intrinsic width, such as with a solid color. So make sure to pass values greater than 1 to Bitmap.createBitmap() method
This error you are getting because d.getIntrinsicWidth(), d.getIntrinsicHeight() returning 0 try to put some constant value and then check like 100.
I am trying to use an AsyncTask to convert an image URL to a bitmap in order to set it to an image. I don't understand how to get the bitmap out of the AsyncTask so that I can set it to my the images I am creating in a loop. I also have tried to set the bitmap to the image inside AsyncTask. My understanding is that everything must be done inside AsyncTask but I am unable to reference the images I want to set the value for.
I have researched the URL to bitmap conversion and the AsyncTask but I can't figure out how to combine them to get what I want. This has to be a fairly common task. Why is it so difficult?
How do I reference my images in AsyncTask?
Can I return my bitmap and then set it to the image outside of AsyncTask?
Is there an easier way to set a URL as an image source?
I have included what I have so far.
Thank you for your help and taking the time to read this.
class BitmapTaks extends AsyncTask<String, Void, Bitmap> {
public Bitmap doInBackground(String... urls) {
Bitmap bm = null;
try {
URL aURL = new URL(urls[0]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("img", "Error getting bitmap", e);
}
return bm;
}
protected void onPostExecute(Bitmap bm) {
//do something after execute
}
}
Simply define final ImageView variable linked to the view you want to fill with the Bitmap:
//inside some method e.g. onCreate()
final ImageView imageView = (ImageView) findViewById(R.id.myPrettyImage);
new AsyncTask<String, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(String... params) {
/* here's your code */
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
}.execute(/*your params*/);
Or you can create ImageView field in your AsyncTask extended task:
private class ExtendedAsyncTask extends AsyncTask<String, Void, Bitmap> {
private ImageView[] views;
public void ExtendedAsyncTask(ImageView[] views) {
this.views = views;
}
#Override
protected Bitmap doInBackground(String... params) {
/* your code here */
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
for (ImageView view: views) {
view.setImageBitmap(bitmap);
}
}
}
and use it:
ExtendedAsyncTask aTask = new ExtendedAsyncTask(new ImageView[]{myImageView1, myImageView2, myImageView3});
aTask.execute(/*some params*/);
This has to be a fairly common task. Why is it so difficult?
I'd really recommend you take a look into the Android Volley library. It's made to abstract away all this AsyncTask boilerplate code. Here's a very nice example of how to set an image bitmap
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
// If you are using normal ImageView
imageLoader.get(Const.URL_IMAGE, new ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Image Load Error: " + error.getMessage());
}
#Override
public void onResponse(ImageContainer response, boolean arg1) {
if (response.getBitmap() != null) {
// load image into imageview
imageView.setImageBitmap(response.getBitmap());
}
}
});
You can read more from here: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
I want to get file from parse to ImageView. I'm try to get by "getDataInBackgound" But when I call to this method' UI is stuck and I get the last image.
ParseFile image = tableParseObjects.getParseFile(PARSE_IMAGES);
image.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
Bitmap bitpic = BitmapFactory.decodeByteArray(data, 0, data.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitpic.compress(Bitmap.CompressFormat.PNG, 100, stream);
vectorSample.setPic(bitpic);
}
});
I think you have to load the image using Picasso or the ImageLoader class. I had the same doubt and I used a ParseImageView too. This is my code:
Retrieve from parse.com the ParseFile (the image) with an asynctask:
public class BackgroundQuery extends AsyncTask<Object, Void, Object> {
private String id;
public BackgroundQuery(String id) {
this.id = id;
}
#Override
protected Object doInBackground(Object... params) {
Object o = null;
try {
ParseQuery<ParseObject> query = ParseQuery.getQuery(params[0]
.getClass().getSimpleName());
query.whereEqualTo("objectId", id);
List<ParseObject> result = query.find();
if (result != null) {
for (ParseObject obj : result) {
o = obj.getParseFile("photo"); // Photo is the ParseFile
}
}
} catch (ParseException e) {
Log.e(TAG, e.getMessage());
}
return o;
}
}
In your layout use this like an ImageView:
<com.parse.ParseImageView
android:id="#id/imgv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true />
Use this line for load the picture in the ParseImageView:
Picasso.with(this).load(parsefile.getUrl()).into(parseimageview);
An alternative to load bigger pics quickly it´s using an ImageLoader. Please check this.
Hope this help :)
I am using an AsyncTask class to download images for my quiz application. This is the class:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap>{
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
// imageView.setImageBitmap(result);
downloaded_image = new BitmapDrawable(result);
//setting question image
question_view.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
}
private Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//--------------------------------------------------
}
}
The image is getting downloaded and I am putting the image inside my Question TextView like this:
downloaded_image = new BitmapDrawable(result);
//setting question image
question_view.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
I am giving a call to this class from my activity like this:
//image download
String imageURL = "http://cache.daylife.com/imageserve/074efG3gPV4oK/50x50.jpg";
image_downloadView.setTag(imageURL);
new DownloadImagesTask().execute(image_downloadView);
I want to pass some extra parameters in order to identify whether I am downloading the image for the question or answer TextViews.
How do I achieve this?
Thanks in advance!
P.S.: I have one question and four options in the application for every set of question.
You can pass parameters to your AsyncTask Constructor.
DownLoadImagesTask dt= new DownLoadImagesTask("hello",1); //passing string and integer value
dt.execute(image_downloadView);
In asynctask
String s;
int value;
public DownLoadImagesTask(String string, int i) {
// TODO Auto-generated constructor stub
s=string;
value=1;
}
You can change the type of your first param to an Object (Or create a custom parameter class/hash - the best option) and pass multiple items to it.
ImageView imgView = (ImageView) findViewById(R.id.imageView1);
String param = "parameter";
MyAsyncTask task = new MyAsyncTask();
task.execute(param, imgView);
private class MyAsyncTask extends AsyncTask<Object, Void, Void> {
private String parameter;
private ImageView imgView;
#Override
protected Void doInBackground(Object... params) {
//Looping option
for (Object object : params) {
if (object instanceof String) {
this.parameter = (String) object;
//do_something
} else if (object instanceof ImageView) {
//do_something_else
}
}
//Direct access option
this.parameter = (String) params[0];
this.imgView = (ImageView) params[1];
return null;
}
}
In your case, you can pass a View
new DownloadImagesTask().execute(image_downloadView, question_resultView);
private class DownloadImagesTask extends AsyncTask<View, Void, Bitmap> {
TextView questionView = null;
ImageView imageView = null;
#Override
protected Bitmap doInBackground(View... views) {
for (View view : views) {
if (view instanceof ImageView) {
this.imageView = (ImageView) view;
} else if (view instanceof TextView) {
this.questionView = (TextView) view;
}
}
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
// imageView.setImageBitmap(result);
downloaded_image = new BitmapDrawable(result);
//setting question image
questionView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
}
}