Here, we are going to make an application of the “Encoding-Decoding” of an image. By making this application we will be able to learn that how we can encode an image in Base64. We will also be decoding our image with help of a button.
Prerequisite:
Before proceeding with this application you should be aware of Base64 in java. If you are not aware of it, use Basic Type Base64 Encoding and Decoding in Java.
What we are going to build in this article?
In this application, we will be using two buttons Encode and Decode to perform their respective operations. Moreover, we will be using a textView to display encoded text and finally an imageView to display the decoded image. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article.
Step by Step Implementation
Step 1: Creating a new project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- You can change the name of the project at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2: Navigate to app > Manifests > AndroidManifest.xml file and add the following permission to it
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Step 3: Working with the activity_main.xml file
Here we will design the user interface of our application. We will be using the following components for their respective works:
- TextView – to show the encoded text
- ImageView – to show the decoded image.
- Button – to encode or decode the image on click.
Navigate to the app > res > layout > activity_main.xml and add the below code to that file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> <!-- Parent Linear layout --> < LinearLayout android:layout_width = "match_parent" android:layout_height = "match_parent" android:background = "#EFA1A1" android:orientation = "vertical" android:padding = "16dp" tools:context = ".MainActivity" > <!-- Layout to display buttons for encoding and decoding--> < LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:orientation = "horizontal" > <!-- Button for encoding of image--> < Button android:id = "@+id/btn_encode" android:layout_width = "0dp" android:layout_height = "wrap_content" android:layout_marginEnd = "4dp" android:layout_marginRight = "4dp" android:layout_weight = "1" android:text = "Encode Image" app:backgroundTint = "#511C1C" /> <!--Button for decoding of image--> < Button android:id = "@+id/btn_decode" android:layout_width = "0dp" android:layout_height = "wrap_content" android:layout_marginStart = "4dp" android:layout_marginLeft = "4dp" android:layout_weight = "1" android:text = "DEcode Image" app:backgroundTint = "#511C1C" /> </ LinearLayout > <!-- Textview to display encoded text--> < TextView android:id = "@+id/textView" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_marginTop = "8dp" android:ellipsize = "end" android:maxLines = "5" /> <!-- Imageview to display decoded image--> < ImageView android:id = "@+id/imageView" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_marginTop = "8dp" android:adjustViewBounds = "true" android:scaleType = "centerCrop" /> </ LinearLayout > |
After implementing the above code, the design of the activity_main.xml file looks like this.
Step 4: Working with MainActivity.java file
Here we write code for the onClickListeners for the Encoding and Decoding buttons, so that they can perform their function. Use the below code in the MainActvity.java file.
Java
import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Base64; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { // Initialize variable Button btnEncode,btnDecode; TextView textView; ImageView imageView; String sImage; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnEncode=findViewById(R.id.btn_encode); btnDecode=findViewById(R.id.btn_decode); textView=findViewById(R.id.textView); imageView= findViewById(R.id.imageView); // Code for Encode button btnEncode.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // check condition if (ContextCompat.checkSelfPermission(MainActivity. this , Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) { // when permission is nor granted // request permission ActivityCompat.requestPermissions(MainActivity. this , new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 100 ); } else { // when permission // is granted // create method selectImage(); } } }); // Code for Decode button btnDecode.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // decode base64 string byte [] bytes=Base64.decode(sImage,Base64.DEFAULT); // Initialize bitmap Bitmap bitmap= BitmapFactory.decodeByteArray(bytes, 0 ,bytes.length); // set bitmap on imageView imageView.setImageBitmap(bitmap); } }); } private void selectImage() { // clear previous data textView.setText( "" ); imageView.setImageBitmap( null ); // Initialize intent Intent intent= new Intent(Intent.ACTION_PICK); // set type intent.setType( "image/*" ); // start activity result startActivityForResult(Intent.createChooser(intent, "Select Image" ), 100 ); } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int [] grantResults) { super .onRequestPermissionsResult(requestCode, permissions, grantResults); // check condition if (requestCode== 100 && grantResults[ 0 ]==PackageManager.PERMISSION_GRANTED) { // when permission // is granted // call method selectImage(); } else { // when permission is denied Toast.makeText( this , "Permission Denied" , Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult( int requestCode, int resultCode, @Nullable Intent data) { super .onActivityResult(requestCode, resultCode, data); // check condition if (requestCode== 100 && resultCode==RESULT_OK && data!= null ) { // when result is ok // initialize uri Uri uri=data.getData(); // Initialize bitmap try { Bitmap bitmap= MediaStore.Images.Media.getBitmap(getContentResolver(),uri); // initialize byte stream ByteArrayOutputStream stream= new ByteArrayOutputStream(); // compress Bitmap bitmap.compress(Bitmap.CompressFormat.JPEG, 100 ,stream); // Initialize byte array byte [] bytes=stream.toByteArray(); // get base64 encoded string sImage= Base64.encodeToString(bytes,Base64.DEFAULT); // set encoded text on textview textView.setText(sImage); } catch (IOException e) { e.printStackTrace(); } } } } |
Output: