Welcome folks today in this blog post we will be seeing how to capture image
from camera and save it in SharedPreferences
and display it in a grid
manner in java. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new android
project inside the android studio and then you will see the below directory
structure as shown below at the end
of the project.
Now we need to edit the activity_main.xml
file where we will have the button
to capture the image from the camera and then we will be having the GridView
widget where we will be displaying 3
images in one column as shown below
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/capture_btn" android:text="Capture Image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"/> <GridView android:id="@+id/image_grid" android:numColumns="3" android:gravity="center" android:stretchMode="columnWidth" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> |
And now we need to edit the MainActivity.java
file and copy paste the following code
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
package com.example.storedataproject; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private static final int REQUEST_IMAGE_CAPTURE = 1; private Button mCaptureBtn; private GridView mImageGrid; private ImageAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mCaptureBtn = findViewById(R.id.capture_btn); mImageGrid = findViewById(R.id.image_grid); mAdapter = new ImageAdapter(this); mImageGrid.setAdapter(mAdapter); mCaptureBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dispatchTakePictureIntent(); } }); mImageGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { String imageUri = mAdapter.getItem(position); Intent intent = new Intent(MainActivity.this, ImageActivity.class); intent.putExtra("imageuri", imageUri); startActivity(intent); } }); } private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } private String saveImageToSharedPreferences(Bitmap imageBitmap) { SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); int nextImageIndex = sharedPreferences.getInt("nextImageIndex", 0); String imageUri = "image_" + nextImageIndex + ".png"; try { FileOutputStream fos = openFileOutput(imageUri, Context.MODE_PRIVATE); imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close(); } catch (IOException e) { e.printStackTrace(); } SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("nextImageIndex", nextImageIndex + 1); editor.apply(); return imageUri; } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); String imageUri = saveImageToSharedPreferences(imageBitmap); mAdapter.addImage(imageUri); mAdapter.notifyDataSetChanged(); } } private static class ImageAdapter extends BaseAdapter { private final Context mContext; private final List<String> mImageUris; public ImageAdapter(Context context) { mContext = context; mImageUris = new ArrayList<>(); // Load existing image URIs from internal storage File[] files = context.getFilesDir().listFiles(); if (files != null) { for (File file : files) { if (file.isFile() && file.getName().startsWith("image_")) { mImageUris.add(file.getName()); } } } } public void addImage(String imageUri) { mImageUris.add(imageUri); } @Override public int getCount() { return mImageUris.size(); } @Override public String getItem(int position) { return mImageUris.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // If it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(250, 250)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); } else { imageView = (ImageView) convertView; } // Decode the image file into a Bitmap object String imageUri = mImageUris.get(position); try { FileInputStream fis = mContext.openFileInput(imageUri); Bitmap bitmap = BitmapFactory.decodeStream(fis); imageView.setImageBitmap(bitmap); fis.close(); } catch (IOException e) { e.printStackTrace(); } return imageView; } } } |
As you can see in the above java
code we are getting the reference of the capture image
button and then we are opening the camera
of the user and taking the picture and after that we are displaying the images
inside the gridView and also we are saving the uri
of the images inside the SharedPreferences
object. And now we need to create another ImageActivity
java class where we will write the java code to open
and preview the image in a full screen when we tap
the image.
ImageActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.example.storedataproject; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ImageActivity extends AppCompatActivity { private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.image_viewer); mImageView = findViewById(R.id.image_view); // Get the URI of the image to display from the Intent Intent intent = getIntent(); String imageUri = intent.getStringExtra("imageuri"); // Decode the image file into a Bitmap object try { FileInputStream fis = openFileInput(imageUri); Bitmap bitmap = BitmapFactory.decodeStream(fis); mImageView.setImageBitmap(bitmap); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
And now we need to make the image_viewer
xml layout file where we will have the ImageView
widget where we will display the captured
image
image_viewer.xml
1 2 3 4 5 6 |
<?xml version="1.0" encoding="utf-8"?> <ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/image_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop"/> |