android retrieve contact image thumbnail - android

I have to display thumbnails of contacts of my contacts in a listview which has a custom cursor adapter implementation. First I did it using asynctask and in the doInBackground method, I used the following snippet to get the bitmap of thumbnail.
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(params[0]));
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(
mContext.getContentResolver(), uri);
if (input != null) {
mThumb = BitmapFactory.decodeStream(input);
} else {
mThumb = defaultPhoto;
}
It gives me correct bitmap.
Later, I came to know about Universal Image Loader. I implemented a custom BaseImageDownlaoder as in the following snippet. `public class ContactImageDownloader extends BaseImageDownloader{
private static final String SCHEME_CONTACT_IMAGE = "content";
private static final String DB_URI_PREFIX = SCHEME_CONTACT_IMAGE + "://";
private Context mContext;
public ContactImageDownloader(Context context) {
super(context);
mContext = context;
}
#Override
protected InputStream getStreamFromOtherSource(String imageUri, Object extra) throws IOException {
if (imageUri.startsWith(DB_URI_PREFIX)) {
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(
mContext.getContentResolver(), Uri.parse(imageUri));
ByteArrayOutputStream output = new ByteArrayOutputStream();
if (input!=null) {
IoUtils.copyStream(input, output);
} else {
//default image
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.wiresimage);
bitmap.compress(CompressFormat.JPEG, BUFFER_SIZE, output);
}
byte[] imageData = output.toByteArray();
input.close();
return new ByteArrayInputStream(imageData);
} else {
return super.getStreamFromOtherSource(imageUri, extra);
}
}`
}
But it doesn't retrieve the image. In the log, it shows java.io.FileNotFoundException: File does not exist; URI: content://com.android.contacts/contacts/567, calling user: com.c
So, now in order to verify my implementation (to check if my custom BaseImageDownloader is wrong), I put the snippet I used in asynctask's doInBackground method to bindView method of cursor adapter. But still, the InputStream is null i.e. FileNotFoundException. But everything works right in Asynctask. Please help. Thanks!

Related

How to display image from database to listview?

I'm new to android development. I am able to restore string from my sqite Database to my listview. Now I want to add image to my listview via the image's path that I saved to my Database(I was able to save the path already, my only problem is how do I add that path in my code below). Here's my code:
private void populateFields() {
// if the row is not null from the database.
if (mRowId != null) {
cursor = studentsDbAdapter.queueStud(mRowId);
String[] from = new String[]{StudentsDbAdapter.KEY_StudentName,StudentsDbAdapter.KEY_StudentID,StudentsDbAdapter.KEY_Course,StudentsDbAdapter.KEY_Year,StudentsDbAdapter.KEY_Contact,StudentsDbAdapter.KEY_Email};
int[] to = new int[]{R.id.textstud,R.id.textstudID};
cursorAdapter = new SimpleCursorAdapter(this, R.layout.stud_row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
}
}
I don't know if this is gonna help but in my other activity where I saved the image's path I was able to restore the image by using the following code:
public void showpic() {
//LoginDataBaseAdapter db = studentsDbAdapter.open();
boolean emptytab = false;
boolean empty = studentsDbAdapter.checkPic(null, emptytab);
//Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
if(empty==false) {
String pathName = studentsDbAdapter.getImapath(studID);
File image = new File(pathName);
if (image.exists()) {
ImageView imageView= (ImageView) findViewById(R.id.studpic);
imageView.setImageBitmap(BitmapFactory.decodeFile(image.getAbsolutePath()));
}
}
}
You have to make custom adapter.
In adapter you can display image like this,
public static void ShowPicture(String fileName, ImageView pic) {
File f = new File(Environment.getExternalStorageDirectory(), fileName);
FileInputStream is = null;
try {
is = new FileInputStream(f);
} catch (FileNotFoundException e) {
Log.d("error: ",String.format( "ShowPicture.java file[%s]Not Found",fileName));
return;
}
Bitmap = BitmapFactory.decodeStream(is, null, null);
pic.setImageBitmap(bm);
}
How are you storing your image in DB ?
If Stored as blob, use BitmapFactory to convert it to Bitmap and set it to ImageView.
Or if it is stored as Base64 encoded string, then decode it and convert it to Bitmap.

Is it possible to Generate a thumbnail from a video url in android

I am working on a video app. I am streaming a video from server link , is it possible for me to generate a video thumbnail from the URL without downloading the video.
Without downloading video you can generate thumbnail from below code:
public static Bitmap retriveVideoFrameFromVideo(String videoPath) throws Throwable
{
Bitmap bitmap = null;
MediaMetadataRetriever mediaMetadataRetriever = null;
try
{
mediaMetadataRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mediaMetadataRetriever.setDataSource(videoPath, new HashMap<String, String>());
else
mediaMetadataRetriever.setDataSource(videoPath);
// mediaMetadataRetriever.setDataSource(videoPath);
bitmap = mediaMetadataRetriever.getFrameAtTime();
} catch (Exception e) {
e.printStackTrace();
throw new Throwable("Exception in retriveVideoFrameFromVideo(String videoPath)" + e.getMessage());
} finally {
if (mediaMetadataRetriever != null) {
mediaMetadataRetriever.release();
}
}
return bitmap;
}
NOTE : Video is stored as Intra and non Intra (Picture frames) getFrameAtTime will return the closest non- Intra frame as Bitmap. So basically it won't download the entire video.
I tried this with glide and it worked , Glide version 4.3.1
GlideApp.with(context)
.asBitmap()
.load(FILE_URL)
.diskCacheStrategy(DiskCacheStrategy.DATA)
.into(iv_picture);
Edit : Glide was working slow for me
The Top answer was not giving result for some videos , here is how i did it
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
//give YourVideoUrl below
retriever.setDataSource("YourVideoUrl", new HashMap<String, String>());
// this gets frame at 2nd second
Bitmap image = retriever.getFrameAtTime(2000000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
//use this bitmap image
It is not possible to create thumbnail from steaming link, you have to show it from server. Better upload a thumbnail along the video.
Use the below code to generate thumbnail
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail("picturePath", MediaStore.Video.Thumbnails.MINI_KIND);
Here's your link:
Android: Is it possible to display video thumbnails?
http://developer.android.com/reference/android/media/ThumbnailUtils.html
In my opinion, Server side should create thumbnail from a video and transfer thumbnail video images through your service.
You can generate Thumbnail from server URL like given below
Add Glide Library then use like this following
RequestOptions requestOptions = new RequestOptions();
requestOptions.isMemoryCacheable();
requestOptions.override(70,70);
Glide.with(context).setDefaultRequestOptions(requestOptions).load(model.getMediaURL()).into(myViewHolder.imageView);
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail("VIDEO FILE ADDRESS", MediaStore.Video.Thumbnails.MINI_KIND);
This method will give you thumbnails of all the video files in your phone... feel free to ask questions
public static Bitmap[] getThumbnail(Context context){
Uri uri=MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection=new String[] { MediaStore.Video.Thumbnails._ID };
Cursor ca = context.getContentResolver().query(uri, projection, null, null, null);
Bitmap[] b=new Bitmap[ca.getCount()];
int i=0;
ca.moveToFirst();
while(i<ca.getCount()) {
int id = ca.getInt(ca.getColumnIndex(MediaStore.Video.Thumbnails._ID));
b[i++]=MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),id, MediaStore.Images.Thumbnails.MINI_KIND, null );
ca.moveToNext();
}
ca.close();
return b;
}
Here is the best solution
"https://img.youtube.com/vi/" + videoID + "/0.jpg"
Here videoID you get from youtube Url.
We fetch all video in Android Phone. http://sunilkmrnishad.blogspot.in/2017/03/read-files-apps-photos-media-from.html
public class ThumbnailExtract extends AsyncTask<String, long[], Bitmap> {
private final String videoUrl;
private final ImageView mThumbnail;
private final boolean mIsVideo;
private MediaMetadataRetriever mmr;
public ThumbnailExtract(String videoLocalUrl, ImageView thumbnail, boolean isVideo) {
this.videoUrl = videoLocalUrl;
mThumbnail = thumbnail;
mIsVideo = isVideo;
if (!isVideo) {
mmr = new MediaMetadataRetriever();
}
}
#Override
protected Bitmap doInBackground(String... params) {
if (!mIsVideo) {
return getBitmap(videoUrl);
} else {
return ThumbnailUtils.createVideoThumbnail(videoUrl,
MediaStore.Images.Thumbnails.MINI_KIND);
}
}
#Override
protected void onPostExecute(Bitmap thumb) {
if (thumb != null) {
mThumbnail.setImageBitmap(thumb);
}
}
private Bitmap getBitmap(String fileUrl) {
mmr.setDataSource(fileUrl);
byte[] data = mmr.getEmbeddedPicture();
Bitmap bitmap = null;
// convert the byte array to a bitmap
if (data != null) {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
return bitmap != null ? ScalingUtilities.createScaledBitmap(bitmap, 40, 40, ScalingUtilities.ScalingLogic.FIT) : bitmap;
}
}

Save array of drawable to file Android

im trying to save an arraylist of drawable to a file.
Here is my class.
public class SeccionItem implements Serializable{
String name;
String text;
ArrayList<Drawable> img;
SeccionItem()
{
img = new ArrayList<Drawable>();
}
}
I have an arraylist of that class and i want to write it to a file using objectoutputstream, but i think that drawable cant be serialized, so can i use another type to store the images? like bitmap?. or is there any other way to store that arraylist? overwriting writeObject method?.
Im using this method to download the images
public static Drawable getBitmap(String image_url) {
try {
URL url = new URL(image_url);
InputStream is = (InputStream)url.getContent();
Drawable b= Drawable.createFromStream(is, " ");
if(b==null){
Log.d("this","null");
}
return b;
}catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
neither Bitmap or Drawable are serializable. You could serialize the information to rebuild your Drawable. For instance you could serialize an ArrayList<Integer> where the Intever is the Drawable's id.
that drawables are downloaded from internet, i want to store it so
next time i dont have to download it again.
So you can store it on the sdcard, and nex time you can check if the file exists or not.
To write a file
public static void copy(InputStream is, File out) throws IOException {
byte[] buffer = new byte[BUFFER_LEN];
FileOutputStream fos = new FileOutputStream(out);
try {
int read = 0;
while ((read = is.read(buffer, 0, BUFFER_LEN)) >= 0) {
fos.write(buffer, 0, read);
}
fos.flush();
} finally {
close(fos);
}
fos = null;
buffer = null;
}

How to Retrieve image from url

I am working on API. We have provided Url of Images. I have to show image from that Url in my list Activity for which custom Adapter is used. How can I set image throw url? I have spent almost two days in it. I used image view in my Activity.
try below code in your activity, you will get Bitmap object, using setImageBitmap(Bitmap bmt) you can do.
Method:
public Bitmap getBitmap(String url) {
Log.d("getBitmap", "getBitmap");
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(new FlushedInputStream(is));
bis.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return bm;
}
inner class:
class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
}
see this complete example
Use this code to get bitmap image from file ,
Bitmap bitmapImage = BitmapFactory.decodeFile(//File path);
imageView.setImageBitmap(bitmapImage);
and you can get file from uri through the below method ,
private File getFileFromUri(Uri uri) throws IOException {
Cursor cursor = managedQuery(uri, null, null, null, null);
if (cursor.getCount() == 0) {
throw new IOException(String.format("cannot find data from %s",
uri.toString()));
} else {
cursor.moveToFirst();
}
String filePath = cursor.getString(cursor
.getColumnIndex(Video.VideoColumns.DATA));
File file = new File(filePath);
cursor.close();
return file;
}
Hope this will be helpful to you

CreateFromStream in Android returning null for certain url

public class TestButton extends Activity {
/** Called when the activity is first created. */
ImageButton imgBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgBtn = (ImageButton) findViewById(R.id.image);
//String url = "http://thenextweb.com/apps/files/2010/03/google_logo.jpg";
String url1 = "http://trueslant.com/michaelshermer/files/2010/03/evil-google.jpg";
Drawable drawable = LoadImage(url1);
imgBtn.setImageDrawable(drawable);
}
private Drawable LoadImage(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (Exception e) {
return null;
}
}
}
Above is the code snippet which I use to load image from web into ImageButton. Most of the images get displayed , but certain urls like the one above i.e. url1 , Drawable.createFromStream returns null !! What is the reason and how to avoid it or overcome this problem ?
I've stumbled upon same problem today. And found an answer, luckily :) There is a bug in SDK, described more or less on that google groups thread.
Workaround that worked for me is:
private static final int BUFFER_IO_SIZE = 8000;
private Bitmap loadImageFromUrl(final String url) {
try {
// Addresses bug in SDK :
// http://groups.google.com/group/android-developers/browse_thread/thread/4ed17d7e48899b26/
BufferedInputStream bis = new BufferedInputStream(new URL(url).openStream(), BUFFER_IO_SIZE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos, BUFFER_IO_SIZE);
copy(bis, bos);
bos.flush();
return BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size());
} catch (IOException e) {
// handle it properly
}
}
private void copy(final InputStream bis, final OutputStream baos) throws IOException {
byte[] buf = new byte[256];
int l;
while ((l = bis.read(buf)) >= 0) baos.write(buf, 0, l);
}
And make sure not to set buffers size to more than 8k, because OS will use default size instead of the one you set (logging that of course, but it took me a while to notice that ;) ).
One more solution is using FlushedInputStream http://code.google.com/p/android/issues/detail?id=6066

Categories

Resources