Wednesday, March 9, 2016

Insert bitmap to MediaStore with title and List images title in MediaStore

It's a following exercise of my old posts "Save Bitmap to storage", "List images in MediaStore.Images.Media" and "Get thumbnails (in MediaStore.Images.Thumbnails) associated with MediaStore.Images.Media", to show how to insert bitmap to MediaStore with title, and list images title in MediaStore.


To insert bitmap to MediaStore, we can call insertImage(ContentResolver cr, String imagePath, String name, String description) or insertImage(ContentResolver cr, Bitmap source, String title, String description) methods of MediaStore.Images.Media. Both of them, we have to provide title (or name) and description. In my understanding, they are some extra info we can pass to MediaStore.

In the insert bitmap side, modify the example in "Save Bitmap to storage" to insert with user editable title. For the second button "Save to MediaStore" only.


MainActivity.java
package com.blogspot.android_er.androidsavebitmap;

import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    ImageView imageView;
    Button btnSaveExternalStorageDirectory;
    Button btnSaveMediaStore;
    Button btnSaveFileAndMediaStore;

    EditText editTextTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextTitle = (EditText)findViewById(R.id.title);

        imageView = (ImageView)findViewById(R.id.image);
        btnSaveExternalStorageDirectory = (Button)findViewById(R.id.saveExternalStorageDirectory);
        btnSaveExternalStorageDirectory.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                /*
                * Save bitmap to ExternalStorageDirectory
                */
                // get bitmap from ImageView
                // not always valid, depends on your drawable
                Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

                //always save as
                String fileName = "test.jpg";

                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

                File ExternalStorageDirectory = Environment.getExternalStorageDirectory();
                File file = new File(ExternalStorageDirectory + File.separator + fileName);

                FileOutputStream fileOutputStream = null;
                try {
                    file.createNewFile();
                    fileOutputStream = new FileOutputStream(file);
                    fileOutputStream.write(bytes.toByteArray());

                    Toast.makeText(MainActivity.this,
                            file.getAbsolutePath(),
                            Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if(fileOutputStream != null){
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }});

        btnSaveMediaStore = (Button)findViewById(R.id.saveMediaStore);
        btnSaveMediaStore.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                /*
                * Save bitmap to MediaStore
                */

                //get bitmap from ImageVIew
                //not always valid, depends on your drawable
                Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

                ContentResolver cr = getContentResolver();
                //Save with user editable title
                String title = editTextTitle.getText().toString();
                String description = "Bitmap saved by Android-er";
                String savedURL = MediaStore.Images.Media
                        .insertImage(cr, bitmap, title, description);

                Toast.makeText(MainActivity.this,
                        savedURL,
                        Toast.LENGTH_LONG).show();

            }});

        btnSaveFileAndMediaStore = (Button)findViewById(R.id.saveExternalStorageDirectoryMediaStore);
        btnSaveFileAndMediaStore.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                /*
                * Save bitmap to ExternalStorageDirectory
                */

                //get bitmap from ImageVIew
                //not always valid, depends on your drawable
                Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

                //always save as
                String fileName = "test.jpg";

                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

                File ExternalStorageDirectory = Environment.getExternalStorageDirectory();
                File file = new File(ExternalStorageDirectory + File.separator + fileName);

                FileOutputStream fileOutputStream = null;
                try {
                    file.createNewFile();
                    fileOutputStream = new FileOutputStream(file);
                    fileOutputStream.write(bytes.toByteArray());

                    ContentResolver cr = getContentResolver();
                    String imagePath = file.getAbsolutePath();
                    String name = file.getName();
                    String description = "My bitmap created by Android-er";
                    String savedURL = MediaStore.Images.Media
                            .insertImage(cr, imagePath, name, description);

                    Toast.makeText(MainActivity.this,
                            savedURL,
                            Toast.LENGTH_LONG).show();

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if(fileOutputStream != null){
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }

            }});
    }
}


layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    tools:context="com.blogspot.android_er.androidsavebitmap.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher" />

    <EditText
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/saveExternalStorageDirectory"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save to ExternalStorageDirectory" />

    <Button
        android:id="@+id/saveMediaStore"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save to MediaStore" />

    <Button
        android:id="@+id/saveExternalStorageDirectoryMediaStore"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save to ExternalStorageDirectory and insert to MediaStore" />
</LinearLayout>


uses-permission of "android.permission.WRITE_EXTERNAL_STORAGE" is needed in AndroidManifest.xml.


download filesDownload the files .


In the List Images in MediaStore:


MainActivity.java
package com.blogspot.android_er.androidlistimages;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    final Uri thumbUri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;;
    final String thumb_DATA = MediaStore.Images.Thumbnails.DATA;
    final String thumb_IMAGE_ID = MediaStore.Images.Thumbnails.IMAGE_ID;
    final Uri sourceUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

    ListView myList;
    SimpleCursorAdapter mySimpleCursorAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myList=(ListView)findViewById(R.id.mylist);

        String[] from = {MediaStore.MediaColumns.TITLE};
        int[] to = {android.R.id.text1};

        CursorLoader cursorLoader = new CursorLoader(
                this,
                sourceUri,
                null,
                null,
                null,
                MediaStore.Images.Media.TITLE);

        Cursor cursor = cursorLoader.loadInBackground();

        mySimpleCursorAdapter = new SimpleCursorAdapter(
                this,
                android.R.layout.simple_list_item_1,
                cursor,
                from,
                to,
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        myList.setAdapter(mySimpleCursorAdapter);
        myList.setOnItemClickListener(myOnItemClickListener);
    }

    AdapterView.OnItemClickListener myOnItemClickListener
            = new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Cursor cursor = mySimpleCursorAdapter.getCursor();
            cursor.moveToPosition(position);

            int int_ID = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media._ID));
            getThumbnail(int_ID);
        }
    };

    private Bitmap getThumbnail(int id){

        String[] thumbColumns = {thumb_DATA, thumb_IMAGE_ID};

        CursorLoader thumbCursorLoader = new CursorLoader(
                this,
                thumbUri,
                thumbColumns,
                thumb_IMAGE_ID + "=" + id,
                null,
                null);

        Cursor thumbCursor = thumbCursorLoader.loadInBackground();

        Bitmap thumbBitmap = null;
        if(thumbCursor.moveToFirst()){
            int thCulumnIndex = thumbCursor.getColumnIndex(thumb_DATA);

            String thumbPath = thumbCursor.getString(thCulumnIndex);

            Toast.makeText(getApplicationContext(),
                    thumbPath,
                    Toast.LENGTH_LONG).show();

            thumbBitmap = BitmapFactory.decodeFile(thumbPath);

            //Create a Dialog to display the thumbnail
            AlertDialog.Builder thumbDialog = new AlertDialog.Builder(MainActivity.this);
            ImageView thumbView = new ImageView(MainActivity.this);
            thumbView.setImageBitmap(thumbBitmap);
            LinearLayout layout = new LinearLayout(MainActivity.this);
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.addView(thumbView);
            thumbDialog.setView(layout);
            thumbDialog.show();

        }else{
            Toast.makeText(getApplicationContext(),
                    "NO Thumbnail!",
                    Toast.LENGTH_LONG).show();
        }

        return thumbBitmap;
    }
}


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    tools:context="com.blogspot.android_er.androidlistimages.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <ListView
        android:id="@+id/mylist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>


uses-permission of "android.permission.READ_EXTERNAL_STORAGE" is needed in AndroidManifest.xml.

download filesDownload the files .

No comments: