/** * 获取本地图片信息 * @param context * @param map */ public static void getImgInfo(Context context, HashMap<String, ArrayList<String>> map) { //获取图片信息表 Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; ContentResolver mContentResolver = context.getContentResolver(); Cursor mCursor = mContentResolver.query(imageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_TAKEN + " DESC"); while (mCursor.moveToNext()) { String imgPath = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA)); //获取图片父路径 String parentPath = new File(imgPath).getParentFile().getName(); if (!map.containsKey(parentPath)) { ArrayList<String> childList = new ArrayList<String>(); childList.add(imgPath); map.put(parentPath, childList); } else { map.get(parentPath).add(imgPath); } } mCursor.close(); }
/** * Used to find out if we are in a situation where the Camera Intent adds to images * to the content store. If we are using a FILE_URI and the number of images in the DB * increases by 2 we have a duplicate, when using a DATA_URL the number is 1. * * @param type FILE_URI or DATA_URL */ private void checkForDuplicateImage(int type) { int diff = 1; Uri contentStore = whichContentStore(); Cursor cursor = queryImgDB(contentStore); int currentNumOfImages = cursor.getCount(); if (type == FILE_URI && this.saveToPhotoAlbum) { diff = 2; } // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL if ((currentNumOfImages - numPics) == diff) { cursor.moveToLast(); int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))); if (diff == 2) { id--; } Uri uri = Uri.parse(contentStore + "/" + id); this.cordova.getActivity().getContentResolver().delete(uri, null, null); cursor.close(); } }
private void takePhoto() { Intent intentPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); ComponentName componentName = intentPhoto.resolveActivity(getPackageManager()); if (componentName != null) { // 使用 lambda 表达式捕获局部变量,避免了将 tmpFile 作为类变量。 File tmpFile = getTempFile(FileType.IMG); if (tmpFile != null) { BuilderUtil.createBuilder(this, intentPhoto) .asIntent() .setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION) .putExtra(MediaStore.EXTRA_OUTPUT, getUri(componentName, tmpFile)) .asBuilder() .forOk((context, intent) -> context.showPicture(tmpFile)) .start(); } } }
/** * 裁剪图片 * * @param uri */ private void cropImage(Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); // 图片处于可裁剪状态 intent.putExtra("crop", "true"); // aspectX aspectY 是宽高的比例 intent.putExtra("aspectX", 4); intent.putExtra("aspectY", 3); // 是否缩放 intent.putExtra("scale", true); // 设置图片的大小,提高头像的上传速度 intent.putExtra("outputX", 500); intent.putExtra("outputY", 500); // 以Uri的方式传递照片 File cropFile = new File(getFilePath() + "crop.jpg"); cropFileUri = Uri.fromFile(cropFile); // 把裁剪好的图片保存到这个路径 intent.putExtra(MediaStore.EXTRA_OUTPUT, cropFileUri); startActivityForResult(intent, CROP_REQUEST); }
private void catchIntent(){ if (file == null) throw new NullPointerException("You need to set the file you want to save the image in."); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); selectedFilePath = file.getPath(); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); if (activity==null) return; // start the image capture Intent if (dialogFragment != null) activity.startActivityFromFragment(dialogFragment, intent, requestCode); else if (fragment!= null) activity.startActivityFromFragment(fragment, intent, requestCode); else activity.startActivityForResult(intent, requestCode); }
public void openCamera() { try { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File image = AndroidUtilities.generatePicturePath(); if (image != null) { if (Build.VERSION.SDK_INT >= 24) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(parentFragment.getParentActivity(), BuildConfig.APPLICATION_ID + ".provider", image)); takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); } currentPicturePath = image.getAbsolutePath(); } parentFragment.startActivityForResult(takePictureIntent, 13); } catch (Exception e) { FileLog.e("tmessages", e); } }
@Override public Cursor loadInBackground() { Cursor albums = super.loadInBackground(); MatrixCursor allAlbum = new MatrixCursor(COLUMNS); int totalCount = 0; String allAlbumCoverPath = ""; if (albums != null) { while (albums.moveToNext()) { totalCount += albums.getInt(albums.getColumnIndex(COLUMN_COUNT)); } if (albums.moveToFirst()) { allAlbumCoverPath = albums.getString(albums.getColumnIndex(MediaStore.MediaColumns.DATA)); } } allAlbum.addRow(new String[]{Album.ALBUM_ID_ALL, Album.ALBUM_ID_ALL, Album.ALBUM_NAME_ALL, allAlbumCoverPath, String.valueOf(totalCount)}); return new MergeCursor(new Cursor[]{allAlbum, albums}); }
public static String getPathOfImage(Context context, Uri uri) throws URISyntaxException { Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); if (cursor.moveToFirst()) { String document_id = cursor.getString(0); document_id = document_id.substring(document_id.lastIndexOf(":") + 1); cursor.close(); cursor = context.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null); if (cursor.moveToFirst()) { String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); cursor.close(); return path; } else return null; } else return null; }
public Object instantiateItem(ViewGroup container, int position){ View v = inflater.inflate(R.layout.viewpager_image,null); ImageView imgView = (ImageView) v.findViewById(R.id.viewPagerImage); //이미지를 가져옴 Uri uri = Uri.fromFile(new File(cards.get(position))); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(inflater.getContext().getContentResolver(),uri); int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth())); Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true); imgView.setImageBitmap(scaled); } catch (IOException e) { e.printStackTrace(); } container.addView(v); return v; }
/** * Start camera intent * Create a temporary file and pass file Uri to camera intent */ private void captureImage() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (intent.resolveActivity(getPackageManager()) != null) { File imageFile = ImageUtils.createImageFile(imageDirectory); if (imageFile != null) { String authority = getPackageName() + ".fileprovider"; Uri uri = FileProvider.getUriForFile(this, authority, imageFile); currentImagePath = "file:" + imageFile.getAbsolutePath(); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, Constants.REQUEST_CODE_CAPTURE); } else { Toast.makeText(this, getString(R.string.error_create_image_file), Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, getString(R.string.error_no_camera), Toast.LENGTH_LONG).show(); } }
public void captureVideo(Activity activity, final ModuleResultListener listener) { if (mIsTakingVideo) { listener.onResult(Util.getError(Constant.CAMERA_BUSY, Constant.CAMERA_BUSY_CODE)); return; } mCaptureVideoStartTime = System.currentTimeMillis(); mIsTakingVideo = true; String fileName = "nat_video_" + new Date().getTime() + ".mov"; Intent intent = new Intent(); intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE); intent.addCategory(Intent.CATEGORY_DEFAULT); try { videoFile = Util.getFile(fileName); } catch (IOException e) { e.printStackTrace(); } Uri uri = Uri.fromFile(videoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); activity.startActivityForResult(intent, Constant.VIDEO_REQUEST_CODE); }
@TargetApi(Build.VERSION_CODES.KITKAT) public void handleImageOnKitKat(Intent data) { String imagePath=null; Uri uri=data.getData(); if (DocumentsContract.isDocumentUri(this,uri)){ //如果是document类型的Uri,则通过document id处理 String docId=DocumentsContract.getDocumentId(uri); if ("com.android.providers.media.documents".equals(uri.getAuthority())){ String id=docId.split(":")[1];//解析数字可是的id String selection=MediaStore.Images.Media._ID+"="+id; imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection); }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){ Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/punlic_downloads"),Long.valueOf(docId)); imagePath=getImagePath(contentUri,null); } }else if ("content".equalsIgnoreCase(uri.getScheme())){ //如果是content类型的Uri,则使用普通方法 imagePath=getImagePath(uri,null); }else if ("file".equalsIgnoreCase(uri.getScheme())){ imagePath=uri.getPath(); } displayImage(imagePath);//根据图片路径显示图片 }
public void captureImage(Activity activity, final ModuleResultListener listener){ if (mIsTakingPhoto) { listener.onResult(Util.getError(Constant.CAMERA_BUSY, Constant.CAMERA_BUSY_CODE)); return; } mCaptureImgStartTime = System.currentTimeMillis(); mIsTakingPhoto = true; String fileName = "nat_img_" + new Date().getTime() + ".jpg"; Intent intent = new Intent(); intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); intent.addCategory(Intent.CATEGORY_DEFAULT); try { finalImageFile = Util.getFile(fileName); } catch (IOException e) { e.printStackTrace(); listener.onResult(Util.getError(Constant.CAMERA_INTERNAL_ERROR, Constant.CAMERA_INTERNAL_ERROR_CODE)); } Uri uri = Uri.fromFile(finalImageFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); activity.startActivityForResult(intent, Constant.IMAGE_REQUEST_CODE); }
private void dispatchTakePictureIntentTest3() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(false); } catch (IOException ex) { // Error occurred while creating the File ex.printStackTrace(); } // Continue only if the File was successfully created if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(this, "com.ge.droid.takingphotossimply.fileprovider", photoFile); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, REQUEST_TAKE_PICTURE_TEST_3); } } }
public static String getRealPathFromURI(Context context, Uri contentURI) throws Exception { String result; String[] proj = {MediaStore.Images.Media.DATA}; try { Cursor cursor = context.getContentResolver().query(contentURI, proj, null, null, null); if (cursor == null || cursor.getCount() == 0) { // Source is Dropbox or other similar local file path result = contentURI.getPath(); } else { cursor.moveToFirst(); int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); result = cursor.getString(idx); if (result == null) { result = contentURI.getPath(); } cursor.close(); } return result; } catch (Exception e) { throw new Exception(e.getMessage()); } }
public static String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] projection = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, projection, null, null, null); if (cursor != null) { int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } return null; } finally { if (cursor != null) { cursor.close(); } } }
public void openGallery() { Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT); getIntent.setType("image/*"); Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); pickIntent.setType("image/*"); Intent chooserIntent = Intent.createChooser(getIntent, "Select An Image"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent}); startActivityForResult(chooserIntent, SELECT_PICTURE); }
/** Get all Camera intents for capturing image using device camera apps. */ public static List<Intent> getCameraIntents( @NonNull Context context, @NonNull PackageManager packageManager) { List<Intent> allIntents = new ArrayList<>(); // Determine Uri of camera image to save. Uri outputFileUri = getCaptureImageOutputUri(context); Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0); for (ResolveInfo res : listCam) { Intent intent = new Intent(captureIntent); intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); intent.setPackage(res.activityInfo.packageName); if (outputFileUri != null) { intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); } allIntents.add(intent); } return allIntents; }
/** * Get the title of the ringtone from the uri of ringtone. * * @param context instance of the caller * @param uri uri of the tone to search * @return title of the tone or return null if no tone found. */ @Nullable public static String getRingtoneName(@NonNull Context context, @NonNull Uri uri) { Ringtone ringtone = RingtoneManager.getRingtone(context, uri); if (ringtone != null) { return ringtone.getTitle(context); } else { Cursor cur = context .getContentResolver() .query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media.TITLE}, MediaStore.Audio.Media._ID + " =?", new String[]{uri.getLastPathSegment()}, null); String title = null; if (cur != null) { title = cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)); cur.close(); } return title; } }
/** * 启动手机相册 */ private void fromGallery() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_NAME))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { startActivityForResult(intent, GALLERY_KITKAT_REQUEST); } else { startActivityForResult(intent, GALLERY_REQUEST); } // Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); // startActivityForResult(intent, 103);103 }
@OnClick(R.id.fab_add_video) public void do_add_video() { Intent capture = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); if (capture.resolveActivity(getPackageManager()) != null) { try { File videoFile = createFileName("traxyvid", ".mp4"); mediaUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", videoFile); capture.putExtra(MediaStore.EXTRA_OUTPUT, mediaUri); startActivityForResult(capture, CAPTURE_VIDEO_REQUEST); } catch (IOException e) { e.printStackTrace(); } } }
/** * 选择相机 */ private void showCameraAction() { // 跳转到系统照相机 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) { // 设置系统相机拍照后的输出路径 // 创建临时文件 try { mTmpFile = FileUtils.createTmpFile(getActivity()); } catch (IOException e) { e.printStackTrace(); } if (mTmpFile != null && mTmpFile.exists()) { cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile)); startActivityForResult(cameraIntent, REQUEST_CAMERA); } else { Toast.makeText(getActivity(), getString(R.string.kf5_image_error), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.kf5_no_camera_hint), Toast.LENGTH_SHORT).show(); } }
private void initiateCameraApp() { // We don't need to ask for permission in this case, because the used calls require // android.permission.WRITE_EXTERNAL_STORAGE only on SDKs *older* than Kitkat, which was // way before permission dialogues have been introduced. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (intent.resolveActivity(getPackageManager()) != null) { File photoFile = null; try { photoFile = createNewImageFile(); } catch (IOException ex) { displayTransientError(R.string.error_media_upload_opening); } // Continue only if the File was successfully created if (photoFile != null) { photoUploadUri = FileProvider.getUriForFile(this, "com.keylesspalace.tusky.fileprovider", photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUploadUri); startActivityForResult(intent, MEDIA_TAKE_PHOTO_RESULT); } } }
private void cameraIntent() throws IOException { if (checkPermissions()){ final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/"; File newdir = new File(dir); newdir.mkdirs(); String file = dir+"profile.jpg"; File newfile = new File(file); try { newfile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } mCurrentPhotoPath = Uri.fromFile(newfile); Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoPath); startActivityForResult(takePictureIntent, REQUEST_CAMERA); } }
public int getOrientation(ContentResolver resolver, Uri uri) { int orientation = 0; try { Cursor cursor = resolver.query(uri, new String[]{MediaStore.Images.ImageColumns.ORIENTATION}, null, null, null); if (cursor.moveToFirst()) orientation = cursor.getInt(0); cursor.close(); } catch (Exception ignore) { try { ExifInterface exif = new ExifInterface(uri.getPath()); orientation = Utility.convertToDegrees(exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0)); } catch (Exception ex) { showOrientationErrorMessage(uri, ex); } } return orientation; }
/** * 拍照 */ private void takePhoto() { try { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); File file = new File(ViewUtil.getAppFile(this, "images")); File mPhotoFile = new File(ViewUtil.getAppFile(this, "images/user_take.jpg")); if (!file.exists()) { boolean result = file.mkdirs(); if (!mPhotoFile.exists()) { boolean b = mPhotoFile.createNewFile(); } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri contentUri = FileProvider.getUriForFile(this, "cn.aaronyi.ameneye.fileprovider", mPhotoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri); } else { intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile)); } startActivityForResult(intent, ACTION_TAKE_PHOTO); } catch (Exception e) { e.printStackTrace(); } }
private void showCameraAction() { if (config.maxNum <= Global.imageList.size()) { AppToast.showToast(String.format(getString(R.string.max_num), config.maxNum)); return; } if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE); return; } Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) { tempFile = new File(FileUtils.getRootPath(getActivity()) + File.separator + getActivity().getString(R.string.app_name) + "_" + System.currentTimeMillis() + ".jpg"); // 创建临时照片文件 FileUtils.createFile(tempFile); Uri uri = FileProvider.getUriForFile(getActivity(), FileUtils.getApplicationId(getActivity()) + ".provider", tempFile); List<ResolveInfo> resInfoList = getActivity().getPackageManager() .queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfoList) { String packageName = resolveInfo.activityInfo.packageName; getActivity().grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); } cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(cameraIntent, REQUEST_CAMERA); } else { AppToast.showToast(R.string.open_camera_failure); } }
private static int countPlaylist(final Context context, final long playlistId) { Cursor c = null; try { c = context.getContentResolver().query( MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId), new String[]{ MediaStore.Audio.Playlists.Members.AUDIO_ID, }, null, null, MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER); if (c != null) { return c.getCount(); } } finally { if (c != null) { c.close(); c = null; } } return 0; }
int[] getArtistsAIDs(){ String searchString = MediaStore.Audio.Media.IS_MUSIC + "=?" + "AND " + MediaStore.Audio.Media.ARTIST_ID + " = " + data[1]; String[] searchPram = new String[]{"1"}; String[] cols = new String[] {MediaStore.Audio.Media._ID}; Cursor cursor = Ui.ef.getBaseContext().getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,cols, searchString ,searchPram,null); int[] AIDs = new int[cursor.getCount()]; int count = 0; for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToNext(); AIDs[count] = cursor.getInt(0); count++; } cursor.close(); return AIDs; }
public void takePicture() { try { mPhotoPath = sdcardPath + "/icon.jpg"; mPhotoFile = new File(mPhotoPath); Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); if (Build.VERSION.SDK_INT >= 23) { Uri uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", mPhotoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); } else { intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile)); } startActivityForResult(intent, 1); } catch (Exception e) { } }
private @Nullable EncodedImage getCameraImage(Uri uri) throws IOException { Cursor cursor = mContentResolver.query(uri, PROJECTION, null, null, null); if (cursor == null) { return null; } try { if (cursor.getCount() == 0) { return null; } cursor.moveToFirst(); final String pathname = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)); if (pathname != null) { return getEncodedImage(new FileInputStream(pathname), getLength(pathname)); } } finally { cursor.close(); } return null; }
private void handleAlbumData(Intent data) { Uri uri = data.getData(); String[] projection = new String[]{ MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query( uri, projection, null, null, null ); if (cursor != null && cursor.moveToFirst()) { int dataIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA); String imagePath = cursor.getString(dataIndex); cursor.close(); showBitmap(imagePath); } }
public void stopVideoRecording(CameraSession session, boolean abandon) { try { CameraInfo info = session.cameraInfo; Camera camera = info.camera; if (camera != null && recorder != null) { MediaRecorder tempRecorder = recorder; recorder = null; tempRecorder.stop(); tempRecorder.release(); camera.reconnect(); camera.startPreview(); session.stopVideoRecording(); } if (!abandon) { final Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(recordedFile, MediaStore.Video.Thumbnails.MINI_KIND); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { onVideoTakeCallback.onFinishVideoRecording(bitmap); } }); } } catch (Exception e) { FileLog.e("tmessages", e); } }
@Test public void testLocalVideoMicroThumbnailReturnsNull() throws Exception { when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true); when( android.media.ThumbnailUtils.createVideoThumbnail( mFile.getPath(), MediaStore.Images.Thumbnails.MICRO_KIND)) .thenReturn(null); mLocalVideoThumbnailProducer.produceResults(mConsumer, mProducerContext); mExecutor.runUntilIdle(); verify(mConsumer).onNewResult(null, Consumer.IS_LAST); verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME); Map<String, String> thumbnailNotFoundMap = ImmutableMap.of(LocalVideoThumbnailProducer.CREATED_THUMBNAIL, "false"); verify(mProducerListener).onProducerFinishWithSuccess( mRequestId, PRODUCER_NAME, thumbnailNotFoundMap); verify(mProducerListener).onUltimateProducerReached(mRequestId, PRODUCER_NAME, false); }
public void capturePhoto(Activity activity, int requestCode) { try { Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (captureIntent.resolveActivity(activity.getPackageManager()) != null) { if (captureUri == null) { captureUri = PersistentBlobProvider.getInstance(context) .createForExternal(ContentType.IMAGE_JPEG); } Log.w(TAG, "captureUri path is " + captureUri.getPath()); captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri); activity.startActivityForResult(captureIntent, requestCode); } } catch (IOException ioe) { Log.w(TAG, ioe); } }
protected InputStream getStreamFromContent(String imageUri) throws FileNotFoundException { ContentResolver res = context.getContentResolver(); Uri uri = Uri.parse(imageUri); if (isVideoContentUri(uri)) { // video thumbnail Long origId = Long.valueOf(uri.getLastPathSegment()); Bitmap bitmap = MediaStore.Video.Thumbnails .getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null); if (bitmap != null) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos); return new ByteArrayInputStream(bos.toByteArray()); } } else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo return getContactPhotoStream(uri); } return res.openInputStream(uri); }
/** * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws FileNotFoundException if the provided URI could not be opened */ protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException { ContentResolver res = context.getContentResolver(); Uri uri = Uri.parse(imageUri); if (isVideoContentUri(uri)) { // video thumbnail Long origId = Long.valueOf(uri.getLastPathSegment()); Bitmap bitmap = MediaStore.Video.Thumbnails .getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null); if (bitmap != null) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0, bos); return new ByteArrayInputStream(bos.toByteArray()); } } else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo return getContactPhotoStream(uri); } return res.openInputStream(uri); }
private void pickImage() { if (mAttachedImages.size() < MAX_ATTACHED_IMAGE_COUNT) { try { Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT); pickIntent.setType("image/*"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { pickIntent.setAction(Intent.ACTION_OPEN_DOCUMENT); pickIntent.addCategory(Intent.CATEGORY_OPENABLE); } mCameraImageUri = Uri.fromFile(ImageUtils.createNewImageFile()); Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraImageUri); Intent chooserIntent = Intent.createChooser(pickIntent, getString(R.string.app_name)); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{takePhotoIntent}); startActivityForResult(chooserIntent, IMAGE_REQUEST_CODE); } catch (IOException e) { Timber.w(e, "Exception while starting image picker in compose screen."); } } }
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; String[] projection = {MediaStore.Images.Media.DATA}; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); return cursor.getString(index); } } finally { if (cursor != null) cursor.close(); } return null; }