Android:如何在ImageView中显示视频缩略图?

时间:2016-05-19 04:44:48

标签: android android-imageview

我浏览过并尝试过如何将录制的视频显示到ImageView而没有成功的多个建议。

此代码适用于拍摄图像并显示图像。视频也会被录制并保存到手机中,但不会显示在ImageView中。有关如何修改我的代码以使视频出现在ImageView中的任何建议吗?

除了:RESULT_LOAD_VID部分之外,一切似乎都能正常工作,该部分应该将选定或录制的视频显示给ImageView。

我收到的错误是:“SkImageDecoder :: Factory返回null”

根据我的理解,这意味着无论出于何种原因,所选/录制的视频位置都没有传递到RESULT_LOAD_VID部分。

感谢任何帮助。

这是我目前的代码:

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

}

2 个答案:

答案 0 :(得分:5)

如果您有视频文件的路径,请使用此方法以位图格式创建缩略图。

public Bitmap createVideoThumbNail(String path){
    return ThumbnailUtils.createVideoThumbnail(path,MediaStore.Video.Thumbnails.MICRO_KIND);
}

并在图片视图中使用它,如: -

ivVideoThumbnail.setImageBitmap(createVideoThumbNail(videoPath));

答案 1 :(得分:2)

  • 下载picasso jar文件并将该jar文件放入" libs"夹
  • 使用毕加索下载图片
  • 使用方法extractYoutubeId(url)从YoutubeVideo Url
  • 中提取youtube id

要获取youtube视频的图片,请使用指定的链接,并将youtube id放在该网址中,如下所示:"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>