Подтвердить что ты не робот

Android: Позвольте пользователю выбрать изображение или видео из галереи

Можно ли запустить галерею таким образом, чтобы отображались изображения и видео?

Спасибо

4b9b3361

Ответ 1

Выберите аудиофайл из галереи:

//Use MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);

Выберите видеофайл из галереи:

//Use MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);

Выберите изображение из галереи:

//Use  MediaStore.Images.Media.EXTERNAL_CONTENT_URI
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

Выберите медиафайлы или изображения:

 Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");

Ответ 2

Вы запускаете галерею как таковую:

Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/* video/*");
startActivityForResult(pickIntent, IMAGE_PICKER_SELECT);

то в вашем onActivityResult вы можете проверить, было ли выбрано видео или изображение, сделав это:

public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode == RESULT_OK) {
    Uri selectedMediaUri = data.getData();
    if (selectedMediaUri.toString().contains("image")) {
        //handle image
    } else  if (selectedMediaUri.toString().contains("video")) {
        //handle video
    }
}

Ответ 3

(EDIT: я больше не использую его, мы вернулись к двум вариантам "выбрать изображение" и "выбрать видео". Проблема была в том, что у некоторых телефонов Sony. Таким образом, это не решение на 100% ниже, будьте осторожны!)

Это то, что я использую:

if (Build.VERSION.SDK_INT < 19) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/* video/*");
    startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_picture)), SELECT_GALLERY);
} else {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"image/*", "video/*"});
    startActivityForResult(intent, SELECT_GALLERY_KITKAT);
}

Ключ здесь intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"image/*", "video/*"});

Ответ 4

intent.setType("*/*");

Это представляет пользователю диалог, но работает, по крайней мере, с ICS. Не тестировались на других платформах.

Ответ 5

Когда вам нужно определить, какой контент был возвращен, вы можете сделать это с помощью средства определения содержимого, чтобы получить тип MIME возвращаемого содержимого:

if( data != null) {
    Uri selectedUri = data.getData();   
    String[] columns = { MediaStore.Images.Media.DATA,
                         MediaStore.Images.Media.MIME_TYPE };

    Cursor cursor = getContentResolver().query(selectedUri, columns, null, null, null);
    cursor.moveToFirst();

    int pathColumnIndex     = cursor.getColumnIndex( columns[0] );
    int mimeTypeColumnIndex = cursor.getColumnIndex( columns[1] );

    String contentPath = cursor.getString(pathColumnIndex);
    String mimeType    = cursor.getString(mimeTypeColumnIndex);
    cursor.close();

    if(mimeType.startsWith("image")) {
          //It an image
    }
    else if(mimeType.startsWith("video")) {
         //It a video
    }       
}
else {
    // show error or do nothing
}

Ответ 6

CoolIris, который пришел с моей вкладкой галактики, может это сделать. Однако cooliris на моем acer beouch не будет: S На моей веху вы не можете запустить галерею с намерением захвата видеоролика, но когда вы запустите его на URL-адресе изображений, вы можете выбрать видео, и оно также вернет URL-адрес видео.

Ответ 7

Вам нужно использовать следующее в качестве набора Intent

Intent photoLibraryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoLibraryIntent.setType("image/* video/*");

Ответ 8

Нет, это невозможно в приложении Gallery. Вы можете попробовать и найти приложение, которое делает это.

Ответ 9

private static final String TAG = MainActivity.class.getSimpleName();

    public Button buttonUpload;
    public Button buttonChoose;
    public VideoView vdoView;
    private ImageView imageView;
    private ProgressDialog progressBar;
    public String path=null;
    long totalSize = 0;
    String mediapath;
    public static final String KEY_VIDEO = "video";
    public static final String KEY_NAME = "name";

    private int PICK_IMAGE_REQUEST = 1;

    private int serverResponseCode;
    private Bitmap bitmap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.edittext);
        buttonChoose=(Button)findViewById(R.id.buttonChoosevdo);
        buttonUpload = (Button) findViewById(R.id.buttonUpload);

        vdoView = (VideoView) findViewById(R.id.videoView);
        buttonChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showFileChooser();
            }
        });
        buttonUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               uploadVideo();
            }
        });

    }

    public void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("video/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            try
            {
                path = data.getData().toString();
                vdoView.setVideoPath(path);
                vdoView.requestFocus();
                vdoView.start();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
    public String uploadVideo() {

        String UPLOAD_URL = "http://192.168.10.15/uploadVideo.php";
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        //Log.d(TAG,path);
       File sourceFile = new File(path);
       if (!sourceFile.isFile()) {
            Log.e("Huzza ->>>>)}]------> ", "Source File Does not exist");
            return null;
        }
        String fileName = path;
        //Log.d(TAG,fileName);
        try {
            FileInputStream fileInputStream = new FileInputStream(path);
           Log.d(TAG, String.valueOf(fileInputStream));
            URL url = new URL(UPLOAD_URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("myFile", fileName);
            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + fileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            Log.i("Huzza", "Initial .available : " + bytesAvailable);

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            serverResponseCode = conn.getResponseCode();
            Log.d(TAG, String.valueOf(serverResponseCode));
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (serverResponseCode == 200) {
            StringBuilder sb = new StringBuilder();
            try {
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn
                        .getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    sb.append(line);
                }
                rd.close();
            } catch (IOException ioex) {
            }
            return sb.toString();
        }else {
            return "Could not upload";
        }
    }