Example usage for android.media ThumbnailUtils createVideoThumbnail

List of usage examples for android.media ThumbnailUtils createVideoThumbnail

Introduction

In this page you can find the example usage for android.media ThumbnailUtils createVideoThumbnail.

Prototype

public static Bitmap createVideoThumbnail(String filePath, int kind) 

Source Link

Document

Create a video thumbnail for a video.

Usage

From source file:Main.java

public static Bitmap getVideoImage(String urlPath) {
    Bitmap bitmap = null;//from  w  ww .  j  av a 2  s.c  om
    bitmap = ThumbnailUtils.createVideoThumbnail(urlPath, MediaStore.Images.Thumbnails.MICRO_KIND);
    bitmap = ThumbnailUtils.extractThumbnail(bitmap, 100, 80, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    return bitmap;
}

From source file:com.dycody.android.idealnote.utils.BitmapHelper.java

/**
 * Retrieves a the bitmap relative to attachment based on mime type
 *//* w  w  w.j a v a2s . co m*/
public static Bitmap getBitmapFromAttachment(Context mContext, Attachment mAttachment, int width, int height) {
    Bitmap bmp = null;
    String path;
    mAttachment.getUri().getPath();

    // Video
    if (Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) {
        // Tries to retrieve full path from ContentResolver if is a new video
        path = StorageHelper.getRealPathFromURI(mContext, mAttachment.getUri());
        // .. or directly from local directory otherwise
        if (path == null) {
            path = FileHelper.getPath(mContext, mAttachment.getUri());
        }
        bmp = ThumbnailUtils.createVideoThumbnail(path, Thumbnails.MINI_KIND);
        if (bmp == null) {
            return null;
        } else {
            bmp = BitmapUtils.createVideoThumbnail(mContext, bmp, width, height);
        }

        // Image
    } else if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type())
            || Constants.MIME_TYPE_SKETCH.equals(mAttachment.getMime_type())) {
        try {
            bmp = BitmapUtils.getThumbnail(mContext, mAttachment.getUri(), width, height);
        } catch (NullPointerException e) {
            bmp = null;
        }

        // Audio
    } else if (Constants.MIME_TYPE_AUDIO.equals(mAttachment.getMime_type())) {
        bmp = ThumbnailUtils
                .extractThumbnail(
                        BitmapUtils.decodeSampledBitmapFromResourceMemOpt(mContext.getResources()
                                .openRawResource(com.dycody.android.idealnote.R.raw.play), width, height),
                        width, height);

        // File
    } else if (Constants.MIME_TYPE_FILES.equals(mAttachment.getMime_type())) {

        // vCard
        if (Constants.MIME_TYPE_CONTACT_EXT.equals(FilenameUtils.getExtension(mAttachment.getName()))) {
            bmp = ThumbnailUtils
                    .extractThumbnail(
                            BitmapUtils.decodeSampledBitmapFromResourceMemOpt(mContext.getResources()
                                    .openRawResource(com.dycody.android.idealnote.R.raw.vcard), width, height),
                            width, height);
        } else {
            bmp = ThumbnailUtils
                    .extractThumbnail(
                            BitmapUtils.decodeSampledBitmapFromResourceMemOpt(mContext.getResources()
                                    .openRawResource(com.dycody.android.idealnote.R.raw.files), width, height),
                            width, height);
        }
    }

    return bmp;
}

From source file:it.feio.android.omninotes.utils.BitmapHelper.java

/**
 * Retrieves a the bitmap relative to attachment based on mime type
 *//*from  ww w. ja v a2s  .c  om*/
public static Bitmap getBitmapFromAttachment(Context mContext, Attachment mAttachment, int width, int height) {
    Bitmap bmp = null;
    String path;
    mAttachment.getUri().getPath();

    // Video
    if (Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) {
        // Tries to retrieve full path from ContentResolver if is a new video
        path = StorageHelper.getRealPathFromURI(mContext, mAttachment.getUri());
        // .. or directly from local directory otherwise
        if (path == null) {
            path = FileHelper.getPath(mContext, mAttachment.getUri());
        }
        bmp = ThumbnailUtils.createVideoThumbnail(path, Thumbnails.MINI_KIND);
        if (bmp == null) {
            return null;
        } else {
            bmp = BitmapUtils.createVideoThumbnail(mContext, bmp, width, height);
        }

        // Image
    } else if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type())
            || Constants.MIME_TYPE_SKETCH.equals(mAttachment.getMime_type())) {
        try {
            bmp = BitmapUtils.getThumbnail(mContext, mAttachment.getUri(), width, height);
        } catch (NullPointerException e) {
            bmp = null;
        }

        // Audio
    } else if (Constants.MIME_TYPE_AUDIO.equals(mAttachment.getMime_type())) {
        bmp = ThumbnailUtils.extractThumbnail(
                BitmapUtils.decodeSampledBitmapFromResourceMemOpt(
                        mContext.getResources().openRawResource(R.drawable.play), width, height),
                width, height);

        // File
    } else if (Constants.MIME_TYPE_FILES.equals(mAttachment.getMime_type())) {

        // vCard
        if (Constants.MIME_TYPE_CONTACT_EXT.equals(FilenameUtils.getExtension(mAttachment.getName()))) {
            bmp = ThumbnailUtils.extractThumbnail(
                    BitmapUtils.decodeSampledBitmapFromResourceMemOpt(
                            mContext.getResources().openRawResource(R.drawable.vcard), width, height),
                    width, height);
        } else {
            bmp = ThumbnailUtils.extractThumbnail(
                    BitmapUtils.decodeSampledBitmapFromResourceMemOpt(
                            mContext.getResources().openRawResource(R.drawable.files), width, height),
                    width, height);
        }
    }

    return bmp;
}

From source file:com.lewie9021.videothumbnail.VideoThumbnail.java

public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {/* w  w  w  . ja  v  a 2  s. c  o  m*/
        // Action is 'create'
        if (action.equals("create")) {
            Uri fileURI = Uri.fromFile(new File(args.getString(0)));
            String filePath = args.getString(0).replace(fileURI.getScheme() + ":", "");
            Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MINI_KIND);

            callbackContext.success(encodeTobase64(thumbnail));
            return true;
        } else {
            callbackContext.error("Invalid action");
            return false;
        }
    } catch (JSONException e) {
        callbackContext.error("JSON Exception");
        return true;
    }
}

From source file:com.photokandy.PKVideoThumbnail.PKVideoThumbnail.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action        The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackId    The callback id used when calling back into JavaScript.
 * @return              A PluginResult object with a status and message.
 *///from   www  . j a  va2s.  co m
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {
        if (action.equals("createThumbnail")) {
            String sourceVideo = args.getString(0);
            String targetImage = args.getString(1);

            Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(sourceVideo.substring(7),
                    MediaStore.Images.Thumbnails.MINI_KIND);

            FileOutputStream theOutputStream;
            try {
                File theOutputFile = new File(targetImage.substring(7));
                if (!theOutputFile.exists()) {
                    if (!theOutputFile.createNewFile()) {
                        callbackContext.error("Could not save thumbnail.");
                        return true;
                    }
                }
                if (theOutputFile.canWrite()) {
                    theOutputStream = new FileOutputStream(theOutputFile);
                    if (theOutputStream != null) {
                        thumbnail.compress(CompressFormat.JPEG, 75, theOutputStream);
                    } else {
                        callbackContext.error("Could not save thumbnail; target not writeable");
                        return true;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                callbackContext.error("I/O exception saving thumbnail");
                return true;
            }
            callbackContext.success(targetImage);
            return true;

        } else {
            return false;
        }
    } catch (JSONException e) {
        callbackContext.error("JSON Exception");
        return true;
    }
}

From source file:com.afrozaar.jazzfestreporting.ResumableUpload.java

/**
 * Uploads user selected video in the project folder to the user's YouTube account using OAuth2
 * for authentication.//from ww  w  .jav a2  s .  c o  m
 */

public static String upload(YouTube youtube, final InputStream fileInputStream, final long fileSize,
        final Uri mFileUri, final String path, final Context context) {
    final NotificationManager notifyManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    Intent notificationIntent = new Intent(context, ReviewActivity.class);
    notificationIntent.setData(mFileUri);
    notificationIntent.setAction(Intent.ACTION_VIEW);
    Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(path, Thumbnails.MICRO_KIND);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentTitle(context.getString(R.string.youtube_upload))
            .setContentText(context.getString(R.string.youtube_upload_started))
            .setSmallIcon(R.drawable.ic_stat_device_access_video).setContentIntent(contentIntent)
            .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(thumbnail));
    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());

    String videoId = null;
    try {
        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();

        /*
         * Set the video to public, so it is available to everyone (what most people want). This is
         * actually the default, but I wanted you to see what it looked like in case you need to set
         * it to "unlisted" or "private" via API.
         */
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);

        // We set a majority of the metadata with the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();

        /*
         * The Calendar instance is used to create a unique name and description for test purposes, so
         * you can see multiple files being uploaded. You will want to remove this from your project
         * and use your own standard names.
         */
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription(
                "Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());

        // Set your keywords.
        snippet.setTags(Arrays.asList(Constants.DEFAULT_KEYWORD,
                Upload.generateKeywordFromPlaylistId(Constants.UPLOAD_PLAYLIST)));

        // Set completed snippet to the video object.
        videoObjectDefiningMetadata.setSnippet(snippet);

        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                new BufferedInputStream(fileInputStream));
        mediaContent.setLength(fileSize);

        /*
         * The upload command includes: 1. Information we want returned after file is successfully
         * uploaded. 2. Metadata we want associated with the uploaded video. 3. Video file itself.
         */
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status",
                videoObjectDefiningMetadata, mediaContent);

        // Set the upload type and add event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();

        /*
         * Sets whether direct media upload is enabled or disabled. True = whole media content is
         * uploaded in a single request. False (default) = resumable media upload protocol to upload
         * in data chunks.
         */
        uploader.setDirectUploadEnabled(false);

        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    builder.setContentText(context.getString(R.string.initiation_started))
                            .setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                    break;
                case INITIATION_COMPLETE:
                    builder.setContentText(context.getString(R.string.initiation_completed))
                            .setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                    break;
                case MEDIA_IN_PROGRESS:
                    builder.setContentTitle(context.getString(R.string.youtube_upload)
                            + (int) (uploader.getProgress() * 100) + "%")
                            .setContentText(context.getString(R.string.upload_in_progress))
                            .setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                    break;
                case MEDIA_COMPLETE:
                    builder.setContentTitle(context.getString(R.string.yt_upload_completed))
                            .setContentText(context.getString(R.string.upload_completed))
                            // Removes the progress bar
                            .setProgress(0, 0, false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                case NOT_STARTED:
                    Log.d(this.getClass().getSimpleName(), context.getString(R.string.upload_not_started));
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

        // Execute upload.
        Video returnedVideo = videoInsert.execute();
        Log.d(TAG, "Video upload completed");
        videoId = returnedVideo.getId();
        Log.d(TAG, String.format("videoId = [%s]", videoId));
    } catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
        Log.e(TAG, "GooglePlayServicesAvailabilityIOException", availabilityException);
        notifyFailedUpload(context, context.getString(R.string.cant_access_play), notifyManager, builder);
    } catch (UserRecoverableAuthIOException userRecoverableException) {
        Log.i(TAG, String.format("UserRecoverableAuthIOException: %s", userRecoverableException.getMessage()));
        requestAuth(context, userRecoverableException);
    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
        notifyFailedUpload(context, context.getString(R.string.please_try_again), notifyManager, builder);
    }
    return videoId;
}

From source file:org.youtube.Youtube_ResumableUpload.java

/**
 * Uploads user selected video in the project folder to the user's YouTube account using OAuth2
 * for authentication.//from  w w w . j a v a  2s. c om
 */

public static String upload(YouTube youtube, final InputStream fileInputStream, final long fileSize,
        final Uri mFileUri, final String path, final Context context) {
    final NotificationManager notifyManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    Intent notificationIntent = new Intent(context, Youtube_ReviewActivity.class);
    notificationIntent.setData(mFileUri);
    notificationIntent.setAction(Intent.ACTION_VIEW);
    Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(path, Thumbnails.MICRO_KIND);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentTitle(context.getString(R.string.youtube_upload))
            .setContentText(context.getString(R.string.youtube_upload_started))
            .setSmallIcon(R.drawable.ic_stat_device_access_video).setContentIntent(contentIntent)
            .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(thumbnail));
    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());

    String videoId = null;
    try {
        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();

        /*
         * Set the video to public, so it is available to everyone (what most people want). This is
         * actually the default, but I wanted you to see what it looked like in case you need to set
         * it to "unlisted" or "private" via API.
         */
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);

        // We set a majority of the metadata with the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();

        /*
         * The Calendar instance is used to create a unique name and description for test purposes, so
         * you can see multiple files being uploaded. You will want to remove this from your project
         * and use your own standard names.
         */
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription(
                "Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());

        // Set your keywords.
        snippet.setTags(Arrays.asList(Youtube_Constants.DEFAULT_KEYWORD,
                Upload.generateKeywordFromPlaylistId(Youtube_Constants.UPLOAD_PLAYLIST)));

        // Set completed snippet to the video object.
        videoObjectDefiningMetadata.setSnippet(snippet);

        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                new BufferedInputStream(fileInputStream));
        mediaContent.setLength(fileSize);

        /*
         * The upload command includes: 1. Information we want returned after file is successfully
         * uploaded. 2. Metadata we want associated with the uploaded video. 3. Video file itself.
         */
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status",
                videoObjectDefiningMetadata, mediaContent);

        // Set the upload type and add event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();

        /*
         * Sets whether direct media upload is enabled or disabled. True = whole media content is
         * uploaded in a single request. False (default) = resumable media upload protocol to upload
         * in data chunks.
         */
        uploader.setDirectUploadEnabled(false);

        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    builder.setContentText(context.getString(R.string.initiation_started))
                            .setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                    break;
                case INITIATION_COMPLETE:
                    builder.setContentText(context.getString(R.string.initiation_completed))
                            .setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                    break;
                case MEDIA_IN_PROGRESS:
                    builder.setContentTitle(context.getString(R.string.youtube_upload)
                            + (int) (uploader.getProgress() * 100) + "%")
                            .setContentText(context.getString(R.string.upload_in_progress))
                            .setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                    break;
                case MEDIA_COMPLETE:
                    builder.setContentTitle(context.getString(R.string.yt_upload_completed))
                            .setContentText(context.getString(R.string.upload_completed))
                            // Removes the progress bar
                            .setProgress(0, 0, false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                case NOT_STARTED:
                    Log.d(this.getClass().getSimpleName(), context.getString(R.string.upload_not_started));
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

        // Execute upload.
        Video returnedVideo = videoInsert.execute();
        Log.d(TAG, "Video upload completed");
        videoId = returnedVideo.getId();
        Log.d(TAG, String.format("videoId = [%s]", videoId));
    } catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
        Log.e(TAG, "GooglePlayServicesAvailabilityIOException", availabilityException);
        notifyFailedUpload(context, context.getString(R.string.cant_access_play), notifyManager, builder);
    } catch (UserRecoverableAuthIOException userRecoverableException) {
        Log.i(TAG, String.format("UserRecoverableAuthIOException: %s", userRecoverableException.getMessage()));
        requestAuth(context, userRecoverableException);
    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
        notifyFailedUpload(context, context.getString(R.string.please_try_again), notifyManager, builder);
    }
    return videoId;
}

From source file:com.stfalcon.hromadskyipatrol.services.VideoProcessingService.java

private void addVideo(Intent data) {
    DatabasePatrol db = DatabasePatrol.get(this);

    ViolationItem violationItem = data.getParcelableExtra(VideoCaptureActivity.MOVIES_TO_SAVE);

    checkIfFileExist(violationItem.videoUrl);

    String thumbUrl = VideoThumbUtils.makeThumb(ThumbnailUtils.createVideoThumbnail(violationItem.videoUrl,
            MediaStore.Images.Thumbnails.MINI_KIND));

    VideoItem video = new VideoItem();
    video.setId(String.valueOf(System.currentTimeMillis()));
    video.setDate(violationItem.getViolationTime());
    video.setVideoPrevURL(violationItem.videoUrlPrev);
    video.setVideoURL(violationItem.videoUrl);
    video.setLatitude(violationItem.getLat());
    video.setLongitude(violationItem.getLon());
    video.setState(VideoItem.State.SAVING);
    video.setOwnerEmail(ProjectPreferencesManager.getUser(this).getEmail());
    video.setThumb(thumbUrl);//ww w  .  j  a  va2  s  .c  om
    video.setSourceType(VideoItem.SOURCE_TYPE_REGISTRATOR);

    db.addVideo(video);

    addVideoToUI(video.getId());
}

From source file:com.doplgangr.secrecy.FileSystem.storage.java

public static Uri saveThumbnail(Context context, Uri uri, String filename) {
    InputStream stream = null;/* w w w .  j  a va2  s . co m*/
    try {
        stream = context.getContentResolver().openInputStream(uri);
        java.io.File thumbpath = new java.io.File(getAbsTempFolder() + "/" + "_thumb" + filename);
        if (thumbpath.exists())
            storage.purgeFile(thumbpath);
        thumbpath.createNewFile();
        FileOutputStream out = new FileOutputStream(thumbpath);
        Bitmap bitmap = decodeSampledBitmapFromPath(getPath(context, uri), 150, 150);
        if (bitmap == null) { //If photo fails, try Video
            Util.log(getPath(context, uri));
            bitmap = ThumbnailUtils.createVideoThumbnail(getPath(context, uri),
                    MediaStore.Video.Thumbnails.MICRO_KIND);
        }
        if (bitmap == null) {
            out.close();
            storage.purgeFile(thumbpath);
            return null;
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.close();
        return Uri.fromFile(thumbpath);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (stream != null)
            try {
                stream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
    return null;
}

From source file:com.ape.transfer.util.FileIconLoader.java

public static Bitmap getMyVideoThumbnail(String videoPath, int width, int height) {
    File file = new File(videoPath);
    if (!file.exists())
        return null;

    Bitmap bitmap = null;//from  w ww .  jav  a  2 s .c o m
    bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, Images.Thumbnails.MICRO_KIND);
    bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    return bitmap;
}