Thumbnail.java 12.6 KB
package com.sw.laryngoscope.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.provider.MediaStore;

import com.bumptech.glide.annotation.GlideModule;

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//import wseemann.media.FFmpegMediaMetadataRetriever;

@GlideModule
public class Thumbnail {
    public static Bitmap createVideoThumbnailBitmap(FileDescriptor fd, int targetWidth) {
        return createVideoThumbnailBitmap(null, fd, targetWidth);
    }

    public static Bitmap createVideoThumbnailBitmap(String filePath, int targetWidth) {
        return createVideoThumbnailBitmap(filePath, null, targetWidth);
    }

    private static Bitmap createVideoThumbnailBitmap(String filePath, FileDescriptor fd,
            int targetWidth) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            if (filePath != null) {
                retriever.setDataSource(filePath);
            } else {
                retriever.setDataSource(fd);
            }
            bitmap = retriever.getFrameAtTime(-1);
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        if (bitmap == null) return null;

        // Scale down the bitmap if it is bigger than we need.
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        if (width > targetWidth) {
            float scale = (float) targetWidth / width;
            int w = Math.round(scale * width);
            int h = Math.round(scale * height);
            Bitmap b1 = Bitmap.createScaledBitmap(bitmap, w, h, true);
            //Matrix mx = new Matrix();
            //Bitmap.createBitmap(b1, 0, 0, b1.getWidth(), b1.getHeight(), mx, true);
            if (b1 != bitmap) {
                bitmap.recycle();
                bitmap = b1;
            }
        }
        return bitmap;
    }

    public static void createVideoThumbnailBitmap1(final String filePath, final String toFile) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                try {
                    if (filePath != null) {
                        retriever.setDataSource(filePath);
                    }
                    //bitmap = retriever.getFrameAtTime(-1);
                    bitmap = retriever.getFrameAtTime(-1);
                } catch (IllegalArgumentException ex) {
                    // Assume this is a corrupt video file
                } catch (RuntimeException ex) {
                    // Assume this is a corrupt video file.
                } finally {
                    try {
                        retriever.release();
                    } catch (RuntimeException ex) {
                        // Ignore failures while cleaning up.
                    }
                }

                FileOutputStream fos = null;
                Logger.d("----createVideoThumbnailBitmap--------2" + toFile);
                try {
                    fos = new FileOutputStream(toFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    Logger.d("----createVideoThumbnailBitmap--------1");
                }

                try {
                    //if ( bitmap != null ) {
                        bitmap.recycle();
                    //}
                } catch (Exception ex) {
                }
            }
        }).start();
    }

    public static void createVideoThumbnailBitmap(final String filePath, final String toFile, final Bitmap mBitmap) {
        //final String filePath = "/sdcard/DCIM/OCamera/VID_20221103_002616.mp4";

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = null;
                    /*try {
                        bitmap = ThumbnailUtils.createVideoThumbnail(filePath, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
                    } catch (IllegalArgumentException ex) {
                        // Assume this is a corrupt video file
                    } catch (RuntimeException ex) {
                        // Assume this is a corrupt video file.
                    } finally {
                    }*/
                    Logger.d("----createVideoThumbnailBitmap-----bitmap---0" + bitmap);
                    if ( bitmap == null || bitmap.getAllocationByteCount() == 0 ) {
                        try {
                            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                            retriever.setDataSource(filePath);
                            //String duration = retriever.extractMetadata(
                            //        android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
                            //String timeString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                            bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                            retriever.release();
                        } catch (Exception ex) {
                        }
                    }
                    Logger.d("----createVideoThumbnailBitmap-----bitmap---1" + bitmap);
                    if ( bitmap == null || bitmap.getAllocationByteCount() == 0 ) {
                        bitmap = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.MINI_KIND);
                    }

                    /*if ( bitmap == null || bitmap.getAllocationByteCount() == 0 ) {
                        FFmpegMediaMetadataRetriever retriever = new FFmpegMediaMetadataRetriever();
                        try {
                            retriever.setDataSource(filePath);
                            //String timeString = retriever.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION);
                            // 获取总长度
                            //long totalTime = Long.parseLong(timeString) * 1000;
                            //if (totalTime > 0) {
                                bitmap = retriever.getFrameAtTime(0);
                                Logger.d("----createVideoThumbnailBitmap-----bitmap---2" + bitmap);
                            //}
                        } catch (RuntimeException ex) {
                            ex.printStackTrace();
                        } finally {
                            try {
                                retriever.release();
                            } catch (RuntimeException ex) {
                                ex.printStackTrace();
                            }
                        }
                    }*/

                    if ( bitmap == null || bitmap.getAllocationByteCount() == 0 ) {
                        bitmap = mBitmap;
                    }
                    Logger.d("----createVideoThumbnailBitmap-----bitmap---3" + bitmap);

                    FileOutputStream fos = null;
                    Logger.d("----createVideoThumbnailBitmap--------2" + toFile);
                    try {
                        fos = new FileOutputStream(toFile);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Logger.d("----createVideoThumbnailBitmap--------1");
                    }

                    try {
                        //if ( bitmap != null ) {
                        bitmap.recycle();
                        //}
                    } catch (Exception ex) {
                    }

                } catch (Exception ex) {
                    // Assume this is a corrupt video file.
                }
            }
        }).start();
    }

    public static Bitmap createVideoThumbnail(String filePath) {
        // MediaMetadataRetriever is available on API Level 8
        // but is hidden until API Level 10
        Class<?> clazz = null;
        Object instance = null;
        try {
            clazz = Class.forName("android.media.MediaMetadataRetriever");
            instance = clazz.newInstance();

            Method method = clazz.getMethod("setDataSource", String.class);
            method.invoke(instance, filePath);

            // The method name changes between API Level 9 and 10.
            if (Build.VERSION.SDK_INT <= 9) {
                return (Bitmap) clazz.getMethod("captureFrame").invoke(instance);
            } else {
                byte[] data = (byte[]) clazz.getMethod("getEmbeddedPicture").invoke(instance);
                if (data != null) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    if (bitmap != null) return bitmap;
                }
                return (Bitmap) clazz.getMethod("getFrameAtTime").invoke(instance);
            }
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } catch (InstantiationException e) {
            Logger.e("createVideoThumbnail" + e);
        } catch (InvocationTargetException e) {
            Logger.e("createVideoThumbnail" + e);
        } catch (ClassNotFoundException e) {
            Logger.e("createVideoThumbnail" + e);
        } catch (NoSuchMethodException e) {
            Logger.e("createVideoThumbnail" + e);
        } catch (IllegalAccessException e) {
            Logger.e("createVideoThumbnail" + e);
        } finally {
            try {
                if (instance != null) {
                    clazz.getMethod("release").invoke(instance);
                }
            } catch (Exception ignored) {
            }
        }
        return null;
    }

    public static int getVideoDur(String filePath) {
        int dur = 0;
        try {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(filePath);
            String timeString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            retriever.release();
            dur = Integer.parseInt(timeString);
        } catch (Exception ex) {
        }

        return dur;
    }

    public static int getVideoRate(String filePath) {
        int rate = 0;
        try {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(filePath);
            String rateString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE);
            retriever.release();
            rate = Integer.parseInt(rateString);
        } catch (Exception ex) {
        }

        return rate;
    }

    public static int getVideoWidth(String filePath) {
        int width = 0;
        try {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(filePath);
            String widthString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
            retriever.release();
            width = Integer.parseInt(widthString);
        } catch (Exception ex) {
        }

        return width;
    }

    public static int getVideoHeight(String filePath) {
        int height = 0;
        try {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(filePath);
            String heightString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
            retriever.release();
            height = Integer.parseInt(heightString);
        } catch (Exception ex) {
        }

        return height;
    }

    /*bitmap = Glide.with(MyApplication.getContext())
            .setDefaultRequestOptions(
                    new RequestOptions()
                            .frame(4000000)
                            .centerCrop()
            )
            .asBitmap() //必须
            .load(filePath)
            .into(100, 100)
            .get();*/

}