Android: How to display video thumbnail in ImageView?
Asked Answered
D

2

5

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;
    }

}
Dioptase answered 19/5, 2016 at 4:44 Comment(1)
Use glide library #35222518Okechuku
B
12

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));
Broadus answered 19/5, 2016 at 4:52 Comment(0)
C
0

This should work fine

bitmap = ThumbnailUtils.createVideoThumbnail(file, new Size(100, 100), null);
imageview.setImageBitmap(bitmap);
Creepie answered 29/10, 2021 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.