Add image to Media Gallery - Android

parakmiakos picture parakmiakos · Jan 30, 2015 · Viewed 15.9k times · Source

I am trying to add a new image to the gallery. I pick an already existing image though an intent and then resize and compress it.

Then I store the resulting bitmap:

public static File compressAndSaveImage(Context ctx, Uri imageUri) throws FileNotFoundException {
    File file = null;

    if (imageUri != null) {
        ContextWrapper cw = new ContextWrapper(ctx);
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        file = new File(directory, imageUri.getLastPathSegment());
        System.out.println("storing to " + file);

        InputStream input = ctx.getContentResolver().openInputStream(imageUri);
        Bitmap b = ImageManager.resize(BitmapFactory.decodeStream(input),
                ctx.getResources().getDimension(R.dimen.player_thumb_w),
                ctx.getResources().getDimension(R.dimen.player_thumb_h));

        FileOutputStream fos = new FileOutputStream(file);
        if (b.compress(Bitmap.CompressFormat.PNG, 100, fos)) {
            System.out.println("Compression success");// bmp is your Bitmap instance
        }
        addPictureToGallery(ctx, file);
    }
    return file;
}

But when I try to add the image to the gallery, I get no errors and the image is not added. I have tried both the methods below:

private static void addPictureToGallery(Context ctx, File filepath) {
//        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//        System.out.println("Publish: " + filepath.exists());
//        System.out.println("Publish: " + filepath.getAbsolutePath());
//        Uri contentUri = Uri.fromFile(filepath);
//        mediaScanIntent.setData(contentUri);
//        ctx.sendBroadcast(mediaScanIntent);
    MediaScannerConnection.scanFile(
            ctx,
            new String[]{filepath.getAbsolutePath()},
            null,
            new MediaScannerConnection.OnScanCompletedListener() {
                @Override
                public void onScanCompleted(String path, Uri uri) {
                    Log.w("mydebug", "file " + path + " was scanned successfully: " + uri);
                }
            });
    }
}

The callback prints the following line:

file /data/data/test.myapps.appname/app_imageDir/6045564126748266738 was scanned successfully: content://media/external/file/7838

What am I missing?

Answer

parakmiakos picture parakmiakos · Jan 31, 2015

Thanks @zgc7009, you set me on the right track. I used some of your code, and this is the end result for anyone else wanting to solve.

The problem indeed was that I was storing the image in my application's local storage.

File storedImagePath = generateImagePath("player", "png");
if (!compressAndSaveImage(storedImagePath, bitmap)) {
    return null;
}
Uri url = addImageToGallery(context.getContentResolver(), "png", storedImagePath);

Where the three methods used are:

Generate Path

private static File getImagesDirectory() {
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + IMAGE_DIR);//Environment.getExternalStorageDirectory()
    if (!file.mkdirs() && !file.isDirectory()) {
        Log.e("mkdir", "Directory not created");
    }
    return file;
}

public static File generateImagePath(String title, String imgType) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
    return new File(getImagesDirectory(), title + "_" + sdf.format(new Date()) + "." + imgType);
}

Compress And Save

public boolean compressAndSaveImage(File file, Bitmap bitmap) {
    boolean result = false;
    try {
        FileOutputStream fos = new FileOutputStream(file);
        if (result = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)) {
            Log.w("image manager", "Compression success");
        }
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

Add To Gallery

public Uri addImageToGallery(ContentResolver cr, String imgType, File filepath) {
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, "player");
    values.put(MediaStore.Images.Media.DISPLAY_NAME, "player");
    values.put(MediaStore.Images.Media.DESCRIPTION, "");
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/" + imgType);
    values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
    values.put(MediaStore.Images.Media.DATA, filepath.toString());

    return cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}