private Cursor query(ContentResolver cr, String bucketId, String[] columns, boolean isDefaultAlbum, boolean isNeedGif, String imageMimeType, String[] args, String order, String selectionId) { Cursor resultCursor; if (isDefaultAlbum) { resultCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, imageMimeType, args, order); } else { if (isNeedGif) { resultCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, selectionId, new String[]{bucketId, args[0], args[1], args[2], args[3]}, order); } else { resultCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, selectionId, new String[]{bucketId, args[0], args[1], args[2]}, order); } } return resultCursor; }
private void queryThumbnails(ContentResolver cr, String[] projection) { Cursor cur = null; try { cur = Images.Thumbnails.queryMiniThumbnails(cr, Images.Thumbnails.EXTERNAL_CONTENT_URI, Images.Thumbnails.MINI_KIND, projection); if (cur != null && cur.moveToFirst()) { do { String imageId = cur.getString(cur.getColumnIndex(Images.Thumbnails.IMAGE_ID)); String imagePath = cur.getString(cur.getColumnIndex(Images.Thumbnails.DATA)); mThumbnailMap.put(imageId, imagePath); } while (cur.moveToNext() && !cur.isLast()); } } finally { if (cur != null) { cur.close(); } } }
private List<ImageMedia> buildAlbumList(ContentResolver cr, String bucketId, int page, @NonNull final IMediaTaskCallback<ImageMedia> callback) { List<ImageMedia> result = new ArrayList<>(); String columns[] = getColumns(); Cursor cursor = null; try { boolean isDefaultAlbum = TextUtils.isEmpty(bucketId); boolean isNeedPaging = mPickerConfig == null || mPickerConfig.isNeedPaging(); boolean isNeedGif = mPickerConfig != null && mPickerConfig.isNeedGif(); int totalCount = getTotalCount(cr, bucketId, columns, isDefaultAlbum, isNeedGif); String imageMimeType = isNeedGif ? SELECTION_IMAGE_MIME_TYPE : SELECTION_IMAGE_MIME_TYPE_WITHOUT_GIF; String[] args = isNeedGif ? SELECTION_ARGS_IMAGE_MIME_TYPE : SELECTION_ARGS_IMAGE_MIME_TYPE_WITHOUT_GIF; String order = isNeedPaging ? Images.Media.DATE_MODIFIED + " desc" + " LIMIT " + page * IMediaTask.PAGE_LIMIT + " , " + IMediaTask.PAGE_LIMIT : Images.Media.DATE_MODIFIED + " desc"; String selectionId = isNeedGif ? SELECTION_ID : SELECTION_ID_WITHOUT_GIF; cursor = query(cr, bucketId, columns, isDefaultAlbum, isNeedGif, imageMimeType, args, order, selectionId); addItem(totalCount, result, cursor, callback); } finally { if (cursor != null) { cursor.close(); } } return result; }
private List<ImageMedia> buildAlbumList(ContentResolver cr, String bucketId, int page, @NonNull final IMediaTaskCallback<ImageMedia> callback) { List<ImageMedia> result = new ArrayList<>(); String columns[] = getColumns(); Cursor cursor = null; try { boolean isDefaultAlbum = TextUtils.isEmpty(bucketId); boolean isNeedPaging = mPickerConfig == null || mPickerConfig.isNeedPaging(); boolean isNeedGif = mPickerConfig != null && mPickerConfig.isNeedGif(); int totalCount = getTotalCount(cr, bucketId, columns, isDefaultAlbum, isNeedGif); String imageMimeType = isNeedGif ? SELECTION_IMAGE_MIME_TYPE : SELECTION_IMAGE_MIME_TYPE_WITHOUT_GIF; String[] args = isNeedGif ? SELECTION_ARGS_IMAGE_MIME_TYPE : SELECTION_ARGS_IMAGE_MIME_TYPE_WITHOUT_GIF; String order = isNeedPaging ? Images.Media.DATE_MODIFIED + DESC + " LIMIT " + page * IMediaTask.PAGE_LIMIT + " , " + IMediaTask.PAGE_LIMIT : Images.Media.DATE_MODIFIED + DESC; String selectionId = isNeedGif ? SELECTION_ID : SELECTION_ID_WITHOUT_GIF; cursor = query(cr, bucketId, columns, isDefaultAlbum, isNeedGif, imageMimeType, args, order, selectionId); addItem(totalCount, result, cursor, callback); } finally { if (cursor != null) { cursor.close(); } } return result; }
protected ParcelFileDescriptor openImageThumbnailCleared(long id, CancellationSignal signal) throws FileNotFoundException { final ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = null; try { cursor = resolver.query(Images.Thumbnails.EXTERNAL_CONTENT_URI, ImageThumbnailQuery.PROJECTION, Images.Thumbnails.IMAGE_ID + "=" + id, null, null); if (cursor.moveToFirst()) { final String data = cursor.getString(ImageThumbnailQuery._DATA); return ParcelFileDescriptor.open( new File(data), ParcelFileDescriptor.MODE_READ_ONLY); } } finally { IoUtils.closeQuietly(cursor); } return null; }
protected int queryOrientationForImage(long id, CancellationSignal signal) { final ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = null; try { cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI, ImageOrientationQuery.PROJECTION, ImageColumns._ID + "=" + id, null, null); if (cursor.moveToFirst()) { return cursor.getInt(ImageOrientationQuery.ORIENTATION); } else { Log.w(TAG, "Missing orientation data for " + id); return 0; } } finally { IoUtils.closeQuietly(cursor); } }
private static BucketEntry[] loadBucketEntriesFromImagesAndVideoTable( ThreadPool.JobContext jc, ContentResolver resolver, int type) { HashMap<Integer, BucketEntry> buckets = new HashMap<Integer, BucketEntry>(64); if ((type & MediaObject.MEDIA_TYPE_IMAGE) != 0) { updateBucketEntriesFromTable( jc, resolver, Images.Media.EXTERNAL_CONTENT_URI, buckets); } if ((type & MediaObject.MEDIA_TYPE_VIDEO) != 0) { updateBucketEntriesFromTable( jc, resolver, Video.Media.EXTERNAL_CONTENT_URI, buckets); } BucketEntry[] entries = buckets.values().toArray(new BucketEntry[buckets.size()]); Arrays.sort(entries, new Comparator<BucketEntry>() { @Override public int compare(BucketEntry a, BucketEntry b) { // sorted by dateTaken in descending order return b.dateTaken - a.dateTaken; } }); return entries; }
public LocalImage(Path path, MediaDataContext application, int id) { super(path, nextVersionNumber()); mApplication = application; ContentResolver resolver = mApplication.getContentResolver(); Uri uri = Images.Media.EXTERNAL_CONTENT_URI; Cursor cursor = LocalAlbum.getItemCursor(resolver, uri, PROJECTION, id); if (cursor == null) { throw new RuntimeException("cannot get cursor for: " + path); } try { if (cursor.moveToNext()) { loadFromCursor(cursor); } else { throw new RuntimeException("cannot find data for: " + path); } } finally { cursor.close(); } }
@Override public void rotate(int degrees) throws Exception { GalleryUtils.assertNotInRenderThread(); Uri baseUri = Images.Media.EXTERNAL_CONTENT_URI; ContentValues values = new ContentValues(); int rotation = (this.rotation + degrees) % 360; if (rotation < 0) rotation += 360; if (mimeType.equalsIgnoreCase("image/jpeg")) { ExifInterface exifInterface = new ExifInterface(filePath); exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(rotation)); exifInterface.saveAttributes(); fileSize = new File(filePath).length(); values.put(Images.Media.SIZE, fileSize); } values.put(Images.Media.ORIENTATION, rotation); mApplication.getContentResolver().update(baseUri, values, "_id=?", new String[]{String.valueOf(id)}); }
/** * 获取文件的路径 * * @param * @return */ public static String getFilePath(Context context, Uri uri) { String filePath = null; if (!TextUtils.isEmpty(uri.getAuthority())) { String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); filePath = cursor.getString(column_index); } else { filePath = uri.getPath(); } return filePath; }
public Loader<Cursor> onCreateLoader(final int id, Bundle bundle) { CursorLoader cursorLoader = null; switch (id) { case LOADER_USER_PHOTOS_EXTERNAL: String selection = null; String[] selectionArgs = null; if (null != bundle && bundle.containsKey(LOADER_PHOTOS_BUCKETS_PARAM)) { selection = Images.Media.BUCKET_ID + " = ?"; selectionArgs = new String[] { bundle .getString(LOADER_PHOTOS_BUCKETS_PARAM) }; } cursorLoader = new PhotupCursorLoader(getActivity(), MediaStoreCursorHelper.MEDIA_STORE_CONTENT_URI, MediaStoreCursorHelper.PHOTOS_PROJECTION, selection, selectionArgs, MediaStoreCursorHelper.PHOTOS_ORDER_BY, false); break; } return cursorLoader; }
public synchronized void cancelThreadDecoding(Thread t, ContentResolver cr) { ThreadStatus status = getOrCreateThreadStatus(t); status.mState = State.CANCEL; if (status.mOptions != null) { status.mOptions.requestCancelDecode(); } // Wake up threads in waiting list notifyAll(); // Since our cancel request can arrive MediaProvider earlier than getThumbnail request, // we use mThumbRequesting flag to make sure our request does cancel the request. try { synchronized (status) { while (status.mThumbRequesting) { Images.Thumbnails.cancelThumbnailRequest(cr, -1, t.getId()); Video.Thumbnails.cancelThumbnailRequest(cr, -1, t.getId()); status.wait(200); } } } catch (InterruptedException ex) { // ignore it. } }
public Bitmap getThumbnail(ContentResolver cr, long origId, int kind, BitmapFactory.Options options, boolean isVideo) { Thread t = Thread.currentThread(); ThreadStatus status = getOrCreateThreadStatus(t); if (!canThreadDecoding(t)) { Log.d(TAG, "Thread " + t + " is not allowed to decode."); return null; } try { synchronized (status) { status.mThumbRequesting = true; } if (isVideo) { return Video.Thumbnails.getThumbnail(cr, origId, t.getId(), kind, null); } else { return Images.Thumbnails.getThumbnail(cr, origId, t.getId(), kind, null); } } finally { synchronized (status) { status.mThumbRequesting = false; status.notifyAll(); } } }
public synchronized static boolean deleteFile(Context context, String path) { File file = new File(path); boolean issucc = false; if (file.exists()) { issucc = file.delete(); if (issucc) { String where = MediaColumns.DATA + "=?"; String[] selectionArgs = new String[] { path }; int columnsNum = context.getContentResolver() .delete(Images.Media.EXTERNAL_CONTENT_URI, where, selectionArgs); if (columnsNum > 0) { return issucc; } else { return false; } } else { return false; } } else { return false; } }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (resultCode == RESULT_CANCELED) { // request was canceled, so do nothing return; } switch (requestCode) { case IMAGE_CHOOSER: // get gp of chosen file Uri selectedMedia = intent.getData(); String sourceMediaPath = MediaUtils.getPathFromUri(this, selectedMedia, Images.Media.DATA); // setting image path setSplashPath(sourceMediaPath); break; } }
/** * Add the entry for the media file to media store. * * @param resolver The The content resolver to use. * @param title The title of the media file. * @param date The date fo the media file. * @param location The location of the media file. * @param orientation The orientation of the media file. * @param width The width of the media file after the orientation is * applied. * @param height The height of the media file after the orientation is * applied. * @param mimeType The MIME type of the data. * @return The content URI of the inserted media file or null, if the image * could not be added. */ private static Uri addImageToMediaStore(ContentResolver resolver, String title, long date, Location location, int orientation, long jpegLength, String path, int width, int height, String mimeType) { // Insert into MediaStore. ContentValues values = getContentValuesForData(title, date, location, orientation, jpegLength, path, width, height, mimeType); Uri uri = null; try { uri = resolver.insert(Images.Media.EXTERNAL_CONTENT_URI, values); } catch (Throwable th) { // This can happen when the external volume is already mounted, but // MediaScanner has not notify MediaProvider to add that volume. // The picture is still safe and MediaScanner will find it and // insert it into MediaProvider. The only problem is that the user // cannot click the thumbnail to review the picture. Log.e(TAG, "Failed to write MediaStore" + th); } return uri; }
private static BucketEntry[] loadBucketEntriesFromImagesAndVideoTable( JobContext jc, ContentResolver resolver, int type) { HashMap<Integer, BucketEntry> buckets = new HashMap<Integer, BucketEntry>(64); if ((type & MediaObject.MEDIA_TYPE_IMAGE) != 0) { updateBucketEntriesFromTable( jc, resolver, Images.Media.EXTERNAL_CONTENT_URI, buckets); } if ((type & MediaObject.MEDIA_TYPE_VIDEO) != 0) { updateBucketEntriesFromTable( jc, resolver, Video.Media.EXTERNAL_CONTENT_URI, buckets); } BucketEntry[] entries = buckets.values().toArray(new BucketEntry[buckets.size()]); Arrays.sort(entries, new Comparator<BucketEntry>() { @Override public int compare(BucketEntry a, BucketEntry b) { // sorted by dateTaken in descending order return b.dateTaken - a.dateTaken; } }); return entries; }
public LocalImage(Path path, GalleryApp application, int id) { super(path, nextVersionNumber()); mApplication = application; ContentResolver resolver = mApplication.getContentResolver(); Uri uri = Images.Media.EXTERNAL_CONTENT_URI; Cursor cursor = LocalAlbum.getItemCursor(resolver, uri, PROJECTION, id); if (cursor == null) { throw new RuntimeException("cannot get cursor for: " + path); } try { if (cursor.moveToNext()) { loadFromCursor(cursor); } else { throw new RuntimeException("cannot find data for: " + path); } } finally { cursor.close(); } }
public LocalAlbum(Path path, GalleryApp application, int bucketId, boolean isImage, String name) { super(path, nextVersionNumber()); mApplication = application; mResolver = application.getContentResolver(); mBucketId = bucketId; mName = name; mIsImage = isImage; if (isImage) { mWhereClause = ImageColumns.BUCKET_ID + " = ?"; mOrderClause = ImageColumns.DATE_TAKEN + " DESC, " + ImageColumns._ID + " DESC"; mBaseUri = Images.Media.EXTERNAL_CONTENT_URI; mProjection = LocalImage.PROJECTION; mItemPath = LocalImage.ITEM_PATH; } else { mWhereClause = VideoColumns.BUCKET_ID + " = ?"; mOrderClause = VideoColumns.DATE_TAKEN + " DESC, " + VideoColumns._ID + " DESC"; mBaseUri = Video.Media.EXTERNAL_CONTENT_URI; mProjection = LocalVideo.PROJECTION; mItemPath = LocalVideo.ITEM_PATH; } mNotifier = new ChangeNotifier(this, mBaseUri, application); }
private void updateExistingItems() { if (mAllItems.size() == 0) return; // Query existing ids. ArrayList<Integer> imageIds = queryExistingIds( Images.Media.EXTERNAL_CONTENT_URI, mMinImageId, mMaxImageId); ArrayList<Integer> videoIds = queryExistingIds( Video.Media.EXTERNAL_CONTENT_URI, mMinVideoId, mMaxVideoId); // Construct the existing items list. mExistingItems.clear(); for (int i = mAllItems.size() - 1; i >= 0; i--) { Path path = mAllItems.get(i); boolean isVideo = mAllItemTypes.get(i); int id = Integer.parseInt(path.getSuffix()); if (isVideo) { if (videoIds.contains(id)) mExistingItems.add(path); } else { if (imageIds.contains(id)) mExistingItems.add(path); } } }
/** * If the <code>sourceUri</code> is a local content Uri, update the * <code>sourceUri</code> to point to the <code>file</code>. * At the same time, the old file <code>sourceUri</code> used to point to * will be removed if it is local. * If the <code>sourceUri</code> is not a local content Uri, then the * <code>file</code> will be inserted as a new content Uri. * @return the final Uri referring to the <code>file</code>. */ public static Uri linkNewFileToUri(Context context, Uri sourceUri, File file, long time, boolean deleteOriginal) { File oldSelectedFile = getLocalFileFromUri(context, sourceUri); final ContentValues values = getContentValues(context, sourceUri, file, time); Uri result = sourceUri; // In the case of incoming Uri is just a local file Uri (like a cached // file), we can't just update the Uri. We have to create a new Uri. boolean fileUri = isFileUri(sourceUri); if (fileUri || oldSelectedFile == null || !deleteOriginal) { result = context.getContentResolver().insert( Images.Media.EXTERNAL_CONTENT_URI, values); } else { context.getContentResolver().update(sourceUri, values, null, null); if (oldSelectedFile.exists()) { oldSelectedFile.delete(); } } return result; }
private static ContentValues getContentValues(Context context, Uri sourceUri, File file, long time) { final ContentValues values = new ContentValues(); time /= 1000; values.put(Images.Media.TITLE, file.getName()); values.put(Images.Media.DISPLAY_NAME, file.getName()); values.put(Images.Media.MIME_TYPE, "image/jpeg"); values.put(Images.Media.DATE_TAKEN, time); values.put(Images.Media.DATE_MODIFIED, time); values.put(Images.Media.DATE_ADDED, time); values.put(Images.Media.ORIENTATION, 0); values.put(Images.Media.DATA, file.getAbsolutePath()); values.put(Images.Media.SIZE, file.length()); final String[] projection = new String[] { ImageColumns.DATE_TAKEN, ImageColumns.LATITUDE, ImageColumns.LONGITUDE, }; SaveImage.querySource(context, sourceUri, projection, new ContentResolverQueryCallback() { @Override public void onCursorResult(Cursor cursor) { values.put(Images.Media.DATE_TAKEN, cursor.getLong(0)); double latitude = cursor.getDouble(1); double longitude = cursor.getDouble(2); // TODO: Change || to && after the default location // issue is fixed. if ((latitude != 0f) || (longitude != 0f)) { values.put(Images.Media.LATITUDE, latitude); values.put(Images.Media.LONGITUDE, longitude); } } }); return values; }
@Override public boolean handleMessage(Message message) { // done on async thread final View view = (View) message.obj; final ImageView thumbImageView = (ImageView) view.findViewById(R.id.thumbnail); Bitmap bitmap = Images.Thumbnails.getThumbnail(context.getContentResolver(), message.what, Images.Thumbnails.MICRO_KIND, null); if (bitmap == null) { bitmap = Video.Thumbnails.getThumbnail(context.getContentResolver(), message.what, Video.Thumbnails.MICRO_KIND, null); } final Bitmap fBitmap = bitmap; // back on UI thread to set the bitmap to the view new Handler(context.getMainLooper()).post(new Runnable() { @Override public void run() { thumbImageView.setImageBitmap(fBitmap); } }); return true; }
/** * * 获取图片地址列表 * * @return list */ public static List<String> getImagesFromMedia() { ArrayList<String> pictures = new ArrayList<String>(); Cursor c = null; try { FileCategoryPageFragment.mAllPictureSize = 0; c = mContentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { "_id", "_data", "_size" }, null, null, null); while (c.moveToNext()) { String path = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); if (!FileUtils.isExists(path)) { continue; } long size = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)); FileCategoryPageFragment.mAllPictureSize += size; pictures.add(path); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) { c.close(); } } return pictures; }
public LocalImage(Path path, WoTuApp application, long id) { super(path, nextVersionNumber()); mApplication = application; ContentResolver resolver = mApplication.getContentResolver(); Uri uri = Images.Media.EXTERNAL_CONTENT_URI; Cursor cursor = LocalAlbum.getItemCursor(resolver, uri, PROJECTION, id); if (cursor == null) { throw new RuntimeException("cannot get cursor for: " + path); } try { if (cursor.moveToNext()) { loadFromCursor(cursor); } else { throw new RuntimeException("cannot find data for: " + path); } } finally { cursor.close(); } }
public HashMap<String, String> getBucketIds() { Uri uri = mBaseUri.buildUpon() .appendQueryParameter("distinct", "true").build(); Cursor c = Images.Media.query( mContentResolver, uri, new String[] { Media.BUCKET_DISPLAY_NAME, Media.BUCKET_ID }, whereClause(), whereClauseArgs(), sortOrder()); try { HashMap<String, String> hash = new HashMap<String, String>(); while (c.moveToNext()) { hash.put(c.getString(1), c.getString(0)); } return hash; } finally { c.close(); } }
private static void gotoGallery(Activity activity, int windowTitleId, int mediaTypes) { Uri target = Images.Media.EXTERNAL_CONTENT_URI.buildUpon() .appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(Intent.ACTION_VIEW, target); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("windowTitle", activity.getString(windowTitleId)); intent.putExtra("mediaTypes", mediaTypes); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Log.e(TAG, "Could not start gallery activity", e); } }
/** * Gets the thumbnail of the given ID of the original image. * * <p> This method wraps around @{code getThumbnail} in {@code * android.provider.MediaStore}. It provides the ability to cancel it. */ public Bitmap getThumbnail(ContentResolver cr, long origId, int kind, BitmapFactory.Options options, boolean isVideo) { Thread t = Thread.currentThread(); ThreadStatus status = getOrCreateThreadStatus(t); if (!canThreadDecoding(t)) { Log.d(TAG, "Thread " + t + " is not allowed to decode."); return null; } try { if (isVideo) { return Video.Thumbnails.getThumbnail(cr, origId, t.getId(), kind, null); } else { return Images.Thumbnails.getThumbnail(cr, origId, t.getId(), kind, null); } } finally { synchronized (status) { status.notifyAll(); } } }
public static String getRealPathFromURI(Activity context, Uri contentUri) { if (context != null && contentUri != null) { String[] proj = { MediaColumns.DATA }; Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null); int s = contentUri.getPath().indexOf("http"); if (s > -1) { return contentUri.getPath().substring(s, contentUri.getPath().length()); } else if (cursor != null) { cursor.moveToFirst(); int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); return cursor.getString(column_index); } else { // Utils.debug("AiOut","cursor null",3); return contentUri.toString().replace("file://", ""); } } else { return ""; } }