Get thumbnail image of video from video url - android

Is it possible to get the thumbnail image from a video Url? I need to thumbnails of videos in a list view.

Yes its possible to get the thumbnail of a video using ThumbnailUtils.
FileOutputStream out;
File land=new File(Environment.getExternalStorageDirectory().getAbsoluteFile()
+"/portland.jpg");// image file use to create image u can give any path.
Bitmap bitmap=ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);//filePath is your video file path.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
out=new FileOutputStream(land.getPath());
out.write(byteArray);
out.close();

If you are specifically asking about youtube videos then there are automatically 4 generated images by Youtube.
http://img.youtube.com/vi/video_url_here/0.jpg
http://img.youtube.com/vi/video_url_here/1.jpg
http://img.youtube.com/vi/video_url_here/2.jpg
http://img.youtube.com/vi/video_url_here/3.jpg
Standard Image sizes
Player Background Thumbnail (480x360 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/0.jpg
Start Thumbnail (120x90 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/1.jpg
Middle Thumbnail (120x90 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/2.jpg
End Thumbnail (120x90 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/3.jpg
High Quality Thumbnail (480x360 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/hqdefault.jpg
Medium Quality Thumbnail (320x180 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/mqdefault.jpg
Normal Quality Thumbnail (120x90 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/default.jpg
Standard Definition Thumbnail (640x480 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/sddefault.jpg
Maximum Resolution Thumbnail (1920x1080 pixels)
http://i1.ytimg.com/vi/G0wGs3useV8/maxresdefault.jpg

It is working in my case
Uri videoUri = data.getData();
String selectedPathVideo="";
selectedPathVideo = ImageFilePath.getPath(getApplicationContext(), videoUri);
Log.i("Image File Path", ""+selectedPathVideo);
try {
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(selectedPathVideo, MediaStore.Video.Thumbnails.MICRO_KIND);
imgFarmerVideo.setImageBitmap(thumb);
} catch (Exception e) {
e.printStackTrace();
}
The Support File
public class ImageFilePath {
/**
* Method for return file path of Gallery image
*
* #param context
* #param uri
* #return path of the selected image file from gallery
*/
public static String getPath(final Context context, final Uri uri)
{
//check here to KITKAT or new version
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}

Try ThumbnailUtils, to get video bitmap from file path
ThumbnailUtils.createVideoThumbnail(filePath,MediaStore.Video.Thumbnails.MINI_KIND);

It is possible to get thumbnail image of video from video url.
If your video type is Vimeo follow below steps:
1)Suppose your Video Url is:
http://player.vimeo.com/video/17314292
2)Get Video Id From Url : eg. 17314292
3)Call WS with Video id and XMl format
http://vimeo.com/api/v2/video/17314292.xml
You will get "thumbnail_small","thumbnail_medium","thumbnail_large" in xml format for video thumb from video id
If your video type is YouTube follow below steps:
1)Video Url :
http://www.youtube.com/embed/Nl2iMF0yKW8
2)Get Video Id From Url : eg. Nl2iMF0yKW8
3)Replace video id in this url
http://i3.ytimg.com/vi/Nl2iMF0yKW8/default.jpg
NOTE:Just replace your id here.

It's very important to identify the components of a problem. I'd actually say you have two separate problems:
Downloading a file from an URL.
Creating a thumbnail image from an incomplete video file.
Look into those two separately, you'll find plenty of information.

To get thumbnail from the URL, i only got one solution till now,
You have to use This library
It Supports file, http, https, mms, mmsh and rtmp protocols
and
It Supports aac, acc+, avi, flac, mp2, mp3, mp4, ogg, 3gp and more! formats (audio and video):

It is possible to get a thumbnail from a video file or url using FFMPEG.
FFMPEG must be built using the NDK (or you can find some Android built FFMPEG binaries). Here is a GitHub project to build FFMPEG:
https://github.com/guardianproject/android-ffmpeg
You can then include the FFMPEG binaries with your app and execute FFMPEG from code in your app to generate an image from the video (local or URL) using a command like:
ffmpeg -i videosite.com/video.flv -ss 00:00:15.000 -vframes 1 thumbnail_out.png
One thing to consider is at what seek time (option -ss) you grab the thumbnail for it to be a meaningful image that represents the video.

Related

in Android 11 i'm not able to get file path from document optio [duplicate]

This question already has answers here:
Android Kotlin: Getting a FileNotFoundException with filename chosen from file picker?
(5 answers)
Android - Get real path of a .txt file selected from the file explorer
(1 answer)
Closed 1 year ago.
check the image for more understanding and thanks in advance. In this screenshot all options are good but I don't want to display the document option here but also need a document to be picked. if there is not any way to hide the option then need help to get the path of file
if (isMediaDocument(uri)) {
Log.e("URI", "" + uri);
final String docId = DocumentsContract.getDocumentId(uri);
Log.e("docId", "" + docId);
final String[] split = docId.split(":");
final String type = split[0];
Log.e("TYPE", "" + type);
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
} /*else if ("document".equals(type)) {
contentUri = uri;
}*/
selection = "_id=?";
selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
if (isGoogleDriveUri(uri)) {
return getDriveFilePath(context, uri);
}
if (isWhatsAppFile(uri)) {
return getFilePathForWhatsApp(context, uri);
}
if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
}
You cannot grey that option out.
And even if you would manage to implement your getRealPathForUri() to deliver a file system path your app would not have read and write access on an Android 11+ device.
So what you want makes no sense.
Use the uri directly.
Every body does now adays.

Proper way to get file path when it's picked using ACTION_GET_CONTENT

I have a file picker implemented in my app like this:
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Title"), FILE_PICK);
It's a known issue that you can't easily get the actual file location this way because Intent will return some weird Uri that you can't really use to create a File object.
I'm using this method to get the actual File path:
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
This works for some files, and for some not. Right now I noticed that it doesn't work when I pick a file from "Downloads" folder. It skips all if statements above and returns null.
What would be the correct way, that would be more reliable to get the actual selected File path?
I have a file picker implemented in my app like this
That is not a "file picker". It is a content picker.
I need a way to be able to pick any file on Android device so that I can upload it to my backend.
Um, well, that depends a fair bit on how literal you are in that sentence.
ACTION_GET_CONTENT is not a problem in general. However, what you get are not necessarily files. However, you can still upload them, assuming that whatever you are using for the uploading allows you to upload from an InputStream. If so, use openInputStream() on a ContentResolver, passing in the Uri, to get the InputStream to use.
If you really need it to be actual files, you can implement a file-picker UI directly in your app. There are libraries for this. However, you will not be able to access all files — in particular, you cannot use this to upload files from removable storage on Android 4.4+.

Android - Convert URI to file path on lollipop

I'm currently attempting to make a media player for audio. I'm currently running lollipop. I ran into a problem setting the dataSource for the media player. First, here's how I set the dataSource:
public void playSong() {
player.reset();
Song selSong = songs.get(songPos);
long currSong = selSong.getId();
//Get Uri of song
Uri trackUri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong);
try {
//Tell the player the song to play
player.setDataSource(getApplicationContext(), trackUri);
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
Log.d("URI Path", trackUri.toString());
}
//Will prepare the song and call onPrepare of player
player.prepareAsync();
}
And the Uri comes out to this:
content://media/external/audio/media/22
I did some research, and from my understanding, after Android 4.1, you can no longer use a URI for the dataSource. When I run this app with the code above, I'll get this error:
E/MediaPlayer﹕ Unable to create media player
E/MUSIC SERVICE﹕ Error setting data source
java.io.IOException: setDataSource failed.: status=0x80000000
at android.media.MediaPlayer.nativeSetDataSource(Native Method)
So now I need to convert the URI to a file path and provide that as the dataSource. And, after more research, it appears kitkat changed the way URI's are provided so its difficult to get the file path from the URI. However, I'm not sure if this change persisted into Android Lollipop 5.0.2.
Essentially, I have the URI of a song, but I need to provide something other than a URI to a dataSource. Is there any way that I can convert the URI on Lollipop, and, if not, how can I provide the dataSource only knowing the song's id? Thanks.
Lollipop decided to take another course with getting files from the system. (Some say it is from KitKat, but I haven't encountered it yet on KitKat). The code below is to get the filepath on lollipop
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(uri))
{
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("audio".equals(type))
{
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
String filePath = getDataColumn(context, contentUri, selection, selectionArgs);
}
isMediaDocument:
public static boolean isMediaDocument(Uri uri)
{
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
getDataColumn:
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs)
{
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst())
{
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
If you still have problems, this is the full answer that checks for images, audio, video, files, etc.

getting Image Thumbnail Android KitKat new storage access framework

As far as I can understand the right way of working with images in Android is to store images Uri in the database, not the image actual path.
Thats how we can get thumbnails for free. And we don't need to prepare them by ourself and hide somewere.
The code below takes thumbnails by Uri.
Code works on android 4.4 and below. But to get image id it doesn't query content provider. It takes ID from Uri itself. The question is: Is it a stable solution, can I rely on it?
#TargetApi(Build.VERSION_CODES.KITKAT)
public static Bitmap getImageThumbnail(Context context, Uri uri){
final ContentResolver resolver = context.getContentResolver();
long id;
try {
if (UIUtils.hasKitKat() && DocumentsContract.isDocumentUri(context, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
id = Long.parseLong(wholeID.split(":")[1]);
}
else if (isMediaUri(uri)){
id = ContentUris.parseId(uri);
}
else return null;
return MediaStore.Images.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Images.Thumbnails.MINI_KIND,
null);
}
catch (Exception e) {
if (DEBUG) Log.e(TAG, "getThumbnail", e);
return null;
}
}
public static boolean isMediaUri(Uri uri) {
return "media".equalsIgnoreCase(uri.getAuthority());
}
you should be using DocumentsContract.getDocumentThumbnail(). this is guaranteed to work with any document uri, not just the builtin media provider.

Store picture on sd directory problem

I'm using the follow code to take a picture using the native camera:
private File mImageFile;
private String mTempImagePath;
public static Uri imageUri;
public void imageFromCamera() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d("fototemp", "No SDCARD");
} else {
mImageFile = new File(Environment.getExternalStorageDirectory()+File.separator+"testFolder", "Pic"+System.currentTimeMillis()+".jpg");
imageUri = Uri.fromFile(mImageFile);
DataClass dc = (DataClass) getApplicationContext();
File tempFile = new File(Environment.getExternalStorageDirectory()+File.separator+"testFolder");
Uri tempUri = Uri.fromFile(tempFile);
dc.setString(DataClass.IMAGE_PATH, tempUri.toString());
Log.d("fototemp", "ImagePath: " + tempUri.toString());
mTempImagePath = mImageFile.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImageFile));
startActivityForResult(intent, 0);
}
}
The ImagePath I print out in the imageFromCamera() method is: 4file:///file%3A/mnt/sdcard/testFolder
Now when I try to access these foto's by using managedQuery I get a different directory.
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI.toString() gives content://media/external/images/thumbnails
What is the difference between these 2 paths? And how can I get the managedQuery to go to the testFolder map to look for pictures?
edit:
I'm trying to connect:
Uri phoneUriII = Uri.parse(Environment.getExternalStorageDirectory()+File.separator+"testFolder");
imagecursor = managedQuery(phoneUriII, img, null,null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
but this code crashes
Sorry don't really understand your question.
Just send this as the URI path.
Environment.getExternalStorageDirectory()+File.separator+"testFolder"
Also
Check if you have the permissions to write to the sd card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I'm using this function in a couple of projects and it works fine.
/**
* Retrieves physical path to the image from content Uri
* #param contentUri
* #return
*/
private String getRealImagePathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

Categories

Resources