I have browsed around and tried multiple suggestions for how to display a recorded video to an ImageView without success.
This code works fine for taking an image and having the image displayed. The video also is recorded and saved to the phone, but it won't show up in the ImageView. Any suggestions on how I can modify my code here to have the Video appear in the ImageView?
Everything seems to work fine besides the: RESULT_LOAD_VID section, which should be displaying the selected or recorded video to the ImageView.
The error I receive is: "SkImageDecoder::Factory returned null"
From what I understand this means that for whatever reason the selected/recorded videos location isn't getting passed on to the RESULT_LOAD_VID section.
Any help is appreciated.
Here is my current code:
public class Media extends AppCompatActivity{
private static int RESULT_LOAD_IMG = 1;
private static int RESULT_LOAD_VID = 1;
String imgDecodableString;
private String selectedImagePath = "";
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
final private int CAPTURE_IMAGE = 2;
private Uri fileUri;
private ImageView mImageView;
Toolbar toolbar;
private String imgPath;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.toolbarmedia, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.camera:
AlertDialog.Builder builder = new AlertDialog.Builder(Media.this);
// builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] { "Take a Photo", "Choose from Gallery" },
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent1, CAPTURE_IMAGE);
break;
case 1:
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
break;
default:
break;
}
}
});
builder.show();
return true;
case R.id.video:
AlertDialog.Builder builder2 = new AlertDialog.Builder(Media.this);
// builder.setTitle("Choose Image Source");
builder2.setItems(new CharSequence[]{"Take a Video", "Select Video from Phone"},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
//create new Intent
Intent intent_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); // create a file to save the video
intent_video.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
intent_video.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
// start the Video Capture Intent
startActivityForResult(intent_video, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
break;
case 1:
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_VID);
break;
default:
break;
}
}
});
builder2.show();
return true;
case R.id.mic:
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media);
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mImageView = (ImageView) findViewById(R.id.media_display);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.media_display);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
System.out.println("path" + selectedImagePath);
mImageView.setImageBitmap(decodeStream(selectedImagePath));
} else if(requestCode == RESULT_LOAD_VID && resultCode == RESULT_OK && null != data){
// Get the Image from data
Uri selectedVideo = data.getData();
String[] filePathColumn = {MediaStore.Video.Media.DATA};
//Get the cursor
Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView vidView = (ImageView) findViewById(R.id.media_display);
// Set the Image in ImageView after decoding the String
vidView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
}else if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Video Saved to Phone", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
Toast.makeText(this, "Video capture failed.",
Toast.LENGTH_LONG).show();
super.onActivityResult(requestCode, resultCode, data);
}
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public Uri setImageUri() {
File file = new File(Environment.getExternalStorageDirectory(), "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public Bitmap decodeStream(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
}
If you have path of your video file then use this method to create thumbnail in bitmap format.
public Bitmap createVideoThumbNail(String path){
return ThumbnailUtils.createVideoThumbnail(path,MediaStore.Video.Thumbnails.MICRO_KIND);
}
and use it in your image view like:-
ivVideoThumbnail.setImageBitmap(createVideoThumbNail(videoPath));
extractYoutubeId(url)
to extract youtube id from YoutubeVideo UrlTo get image of youtube video use given link and put youtube id in that url as below: "http://img.youtube.com/vi/"+extractYoutubeId(url)+"/0.jpg"
Youtube_Video_thumnail
package com.app.download_video_demo;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
// get Picasso jar file and put that jar file in libs folder
public class Youtube_Video_thumnail extends Activity
{
ImageView iv_youtube_thumnail,iv_play;
String videoId;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
super.setContentView(R.layout.youtube_video_activity);
init();
try
{
videoId=extractYoutubeId("http://www.youtube.com/watch?v=t7UxjpUaL3Y");
Log.e("VideoId is->","" + videoId);
String img_url="http://img.youtube.com/vi/"+videoId+"/0.jpg"; // this is link which will give u thumnail image of that video
// picasso jar file download image for u and set image in imagview
Picasso.with(Youtube_Video_thumnail.this)
.load(img_url)
.placeholder(R.drawable.ic_launcher)
.into(iv_youtube_thumnail);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
}
public void init()
{
iv_youtube_thumnail=(ImageView)findViewById(R.id.img_thumnail);
iv_play=(ImageView)findViewById(R.id.iv_play_pause);
}
// extract youtube video id and return that id
// ex--> "http://www.youtube.com/watch?v=t7UxjpUaL3Y"
// videoid is-->t7UxjpUaL3Y
public String extractYoutubeId(String url) throws MalformedURLException {
String query = new URL(url).getQuery();
String[] param = query.split("&");
String id = null;
for (String row : param) {
String[] param1 = row.split("=");
if (param1[0].equals("v")) {
id = param1[1];
}
}
return id;
}
}
youtube_video_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/webvideo_layout2"
android:layout_width="250dp"
android:layout_height="180dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
>
<ImageView
android:id="@+id/img_thumnail"
android:layout_width="250dp"
android:layout_height="180dp"
android:layout_centerInParent="true"
android:scaleType="fitXY" />
<ImageView
android:id="@+id/iv_play_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/icn_play" />
</RelativeLayout>
</LinearLayout>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With