Android Base64 String Image And PDF



Permission

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


Base64imageAndPDFActivity.java

 package hemanth.smartkit.com.Activity;  
 import android.app.Activity;  
 import android.content.DialogInterface;  
 import android.content.Intent;  
 import android.content.pm.PackageManager;  
 import android.graphics.Bitmap;  
 import android.graphics.drawable.BitmapDrawable;  
 import android.graphics.drawable.Drawable;  
 import android.net.Uri;  
 import android.os.Build;  
 import android.os.Bundle;  
 import android.os.Environment;  
 import android.support.v4.app.ActivityCompat;  
 import android.support.v4.content.ContextCompat;  
 import android.support.v7.app.AlertDialog;  
 import android.support.v7.app.AppCompatActivity;  
 import android.util.Base64;  
 import android.util.Log;  
 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.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.IOException;  
 import hemanth.smartkit.com.R;  
 public class Base64imageAndPDFActivity extends AppCompatActivity {  
   EditText PhotoID;  
   ImageView PhotoIDImageView, PhotoIDImageView1;  
   Bitmap myBitmap;  
   Uri picUri;  
   int image_id, Camera = 0, Gallery = 0, PDF = 0;  
   String encodedfile = null;  
   private static final int PERMISSION_REQUEST_CODE = 1;  
   Button Upload;  
   Drawable oldDrawable;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_base64image_and_pdf);  
     if (Build.VERSION.SDK_INT >= 29) {  
       if (checkPermission()) {  
         // Code for above or equal 23 API Oriented Device  
         // Your Permission granted already .Do next code  
       } else {  
         requestPermission(); // Code for permission  
       }  
     } else {  
       // Code for Below 23 API Oriented Device  
       // Do next code  
     }  
     PhotoID = (EditText) findViewById(R.id.PhotoID);  
     PhotoIDImageView = (ImageView) findViewById(R.id.PhotoIDImageView);  
     PhotoIDImageView1 = (ImageView) findViewById(R.id.PhotoIDImageView1);  
     Upload = (Button) findViewById(R.id.Upload);  
     oldDrawable = PhotoIDImageView.getDrawable();  
     PhotoIDImageView.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         getPickImageChooserIntent();  
       }  
     });  
     Upload.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         if (PhotoIDImageView.getDrawable() != oldDrawable) {  
           if (PDF == 1) {  
             new AlertDialog.Builder(Base64imageAndPDFActivity.this)  
                 .setMessage(encodedfile)  
                 .setCancelable(false)  
                 .setPositiveButton("OK", new DialogInterface.OnClickListener() {  
                   public void onClick(DialogInterface dialog, int id) {  
                   }  
                 })  
                 .show();  
           } else {  
             myBitmap = ((BitmapDrawable) PhotoIDImageView1.getDrawable()).getBitmap();  
             ByteArrayOutputStream baos = new ByteArrayOutputStream();  
             myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
             byte[] imageBytes = baos.toByteArray();  
             long lengthbmp = imageBytes.length;  
             Log.e("rlog", String.valueOf(lengthbmp));  
             if (lengthbmp <= 500000) {  
               new AlertDialog.Builder(Base64imageAndPDFActivity.this)  
                   .setMessage(getStringImage(myBitmap))  
                   .setCancelable(false)  
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {  
                     public void onClick(DialogInterface dialog, int id) {  
                     }  
                   })  
                   .show();  
             } else {  
               new AlertDialog.Builder(Base64imageAndPDFActivity.this)  
                   .setMessage("size more than 5mb")  
                   .setCancelable(false)  
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {  
                     public void onClick(DialogInterface dialog, int id) {  
                     }  
                   })  
                   .show();  
             }  
           }  
         } else {  
           new AlertDialog.Builder(Base64imageAndPDFActivity.this)  
               .setMessage("Please select image or pdf")  
               .setCancelable(false)  
               .setPositiveButton("OK", new DialogInterface.OnClickListener() {  
                 public void onClick(DialogInterface dialog, int id) {  
                 }  
               })  
               .show();  
         }  
       }  
     });  
   }  
   public Uri getPickImageResultUri(Intent data) {  
     boolean isCamera = true;  
     if (data != null) {  
       String action = data.getAction();  
       isCamera = action != null && action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
     }  
     return isCamera ? getCaptureImageOutputUri() : data.getData();  
   }  
   /**  
    * Get URI to image received from capture by camera.  
    */  
   private Uri getCaptureImageOutputUri() {  
     Uri outputFileUri = null;  
     File getImage = getExternalCacheDir();  
     if (getImage != null) {  
       outputFileUri = Uri.fromFile(new File(getImage.getPath(), "profile.png"));  
     }  
     return outputFileUri;  
   }  
   private void getPickImageChooserIntent() {  
     final CharSequence[] item = {"Camera", "Gallery", "PDF"};  
     AlertDialog.Builder builder = new AlertDialog.Builder(Base64imageAndPDFActivity.this);  
     builder.setTitle("Choose File to Upload..");  
     builder.setItems(item, new DialogInterface.OnClickListener() {  
       @Override  
       public void onClick(DialogInterface dialog, int i) {  
         if (item[i].equals("Camera")) {  
           Camera = 1;  
           Gallery = 0;  
           PDF = 0;  
           Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
           startActivityForResult(intent, 1);  
         } else if (item[i].equals("Gallery")) {  
           Camera = 0;  
           Gallery = 1;  
           PDF = 0;  
           String[] mimeTypes = {"image/jpeg", "image/png", "image/JPEG", "image/PNG"};  
           Intent intent3 = new Intent();  
           intent3.setType("image/*");  
           intent3.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);  
           intent3.setAction(Intent.ACTION_GET_CONTENT);  
           startActivityForResult(Intent.createChooser(intent3, "Choose File to Upload.."), 1);  
           Uri.parse(Environment.getExternalStorageDirectory().toString());  
         } else if (item[i].equals("PDF")) {  
           Camera = 0;  
           Gallery = 0;  
           PDF = 1;  
           Intent intent3 = new Intent();  
           intent3.setType("application/pdf");  
 //          intent3.addCategory(Intent.CATEGORY_OPENABLE);  
           intent3.setAction(Intent.ACTION_GET_CONTENT);  
           startActivityForResult(Intent.createChooser(intent3, "Choose File to Upload.."), 1);  
           Uri.parse(Environment.getExternalStorageDirectory().toString());  
         }  
       }  
     }).show();  
   }  
   @Override  
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
     Bitmap bitmap1;  
     if (resultCode == Activity.RESULT_OK) {  
       if (getPickImageResultUri(data) != null) {  
         picUri = getPickImageResultUri(data);  
         Uri content_describer = data.getData();  
         try {  
           if (PDF == 1) {  
             Log.i("rlog", "5");  
 //              Uri content_describer = data.getData();  
             Log.i("rlog", content_describer.getPath());  
             if (content_describer.getPath().contains(".pdf") || content_describer.getPath().contains(".PDF")) {  
               String filepath = null;  
               int pos = content_describer.getPath().indexOf("/storage");  
               filepath = content_describer.getPath().substring(pos);  
               File file = new File(filepath);  
               //get the path  
               String s = encodeFileToBase64Binary(file);  
               Log.d("base 64", s);  
               PhotoID.setText(content_describer.getPath());  
               PhotoIDImageView.setImageDrawable(ContextCompat.getDrawable(Base64imageAndPDFActivity.this, R.drawable.pdficon));  
               PhotoIDImageView.requestFocus();  
               PhotoIDImageView1.setVisibility(View.GONE);  
             } else {  
               // Toast.makeText(this, "File name should not contain spaces and numbers", Toast.LENGTH_SHORT).show();  
               new AlertDialog.Builder(Base64imageAndPDFActivity.this)  
                   .setMessage("File name should not contain spaces and numbers")  
                   .setCancelable(false)  
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {  
                     public void onClick(DialogInterface dialog, int id) {  
                     }  
                   })  
                   .show();  
             }  
           } else {  
             Log.i("rlog", "2");  
             myBitmap = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri);  
             PhotoID.setText(picUri.getPath());  
             PhotoIDImageView.setImageDrawable(ContextCompat.getDrawable(Base64imageAndPDFActivity.this, R.drawable.checked));  
             PhotoIDImageView1.setVisibility(View.VISIBLE);  
             PhotoIDImageView1.setImageBitmap(myBitmap);  
             PhotoIDImageView1.requestFocus();  
             if (content_describer.getPath().contains(".pdf") || content_describer.getPath().contains(".PDF")) {  
               new AlertDialog.Builder(Base64imageAndPDFActivity.this)  
                   .setMessage("Please Select image")  
                   .setCancelable(false)  
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {  
                     public void onClick(DialogInterface dialog, int id) {  
                       PhotoID.setText("");  
                       PhotoIDImageView.setImageDrawable(ContextCompat.getDrawable(Base64imageAndPDFActivity.this, R.drawable.cam));  
                       PhotoIDImageView1.setVisibility(View.GONE);  
                       PhotoIDImageView1.setImageDrawable(null);  
                     }  
                   })  
                   .show();  
             }  
           }  
         } catch (IOException e) {  
           e.printStackTrace();  
         } catch (Exception e) {  
           e.printStackTrace();  
         }  
       } else {  
         bitmap1 = (Bitmap) data.getExtras().get("data");  
         myBitmap = bitmap1;  
         PhotoID.setText(bitmap1.toString());  
         PhotoIDImageView.setImageDrawable(ContextCompat.getDrawable(Base64imageAndPDFActivity.this, R.drawable.checked));  
         PhotoIDImageView.setVisibility(View.VISIBLE);  
         PhotoIDImageView1.setImageBitmap(myBitmap);  
         PhotoIDImageView1.requestFocus();  
       }  
     }  
   }  
   public String getStringImage(Bitmap myBitmap) {  
     myBitmap = ((BitmapDrawable) PhotoIDImageView1.getDrawable()).getBitmap();  
     ByteArrayOutputStream baos = new ByteArrayOutputStream();  
     myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
     byte[] imageBytes = baos.toByteArray();  
     long lengthbmp = imageBytes.length;  
     Log.e("rlog", String.valueOf(lengthbmp));  
 //    if(lengthbmp <= 50000 ){  
 //  
 //    }else{  
 //      new AlertDialog.Builder(UpdateProfileActivity.this)  
 //          .setMessage(String.valueOf(lengthbmp))  
 //          .setCancelable(false)  
 //          .setPositiveButton("OK", new DialogInterface.OnClickListener() {  
 //            public void onClick(DialogInterface dialog, int id) {  
 //              mprocessingdialog.dismiss();  
 //            }  
 //          })  
 //          .show();  
 //    }  
     String encodedImage = "data:image/JPEG;base64," + Base64.encodeToString(imageBytes, Base64.DEFAULT);  
     return encodedImage;  
   }  
   private String encodeFileToBase64Binary(File file) {  
     try {  
       FileInputStream fileInputStreamReader = new FileInputStream(file);  
       byte[] bytes = new byte[(int) file.length()];  
       fileInputStreamReader.read(bytes);  
       encodedfile = "data:application/pdf;base64," + Base64.encodeToString(bytes, Base64.DEFAULT).toString();  
     } catch (FileNotFoundException e) {  
       // TODO Auto-generated catch block  
       e.printStackTrace();  
     } catch (IOException e) {  
       // TODO Auto-generated catch block  
       e.printStackTrace();  
     }  
     return encodedfile;  
   }  
   private boolean checkPermission() {  
     int result = ContextCompat.checkSelfPermission(Base64imageAndPDFActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);  
     if (result == PackageManager.PERMISSION_GRANTED) {  
       return true;  
     } else {  
       return false;  
     }  
   }  
   private void requestPermission() {  
     if (ActivityCompat.shouldShowRequestPermissionRationale(Base64imageAndPDFActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  
       Toast.makeText(Base64imageAndPDFActivity.this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();  
     } else {  
       ActivityCompat.requestPermissions(Base64imageAndPDFActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);  
     }  
   }  
 }  


activity_base64image_and_pdf.xml



<?xml version="1.0" encoding="utf-8"?>  
 <android.support.constraint.ConstraintLayout 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"  
   tools:context=".Activity.Base64imageAndPDFActivity">  
   <LinearLayout  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:orientation="vertical">  
     <LinearLayout  
       android:id="@+id/PhotoLinearLayout"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:orientation="horizontal">  
       <android.support.design.widget.TextInputLayout  
         android:id="@+id/PhotoIDTextInputLayout"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:focusable="false">  
         <EditText  
           android:id="@+id/PhotoID"  
           android:layout_width="fill_parent"  
           android:layout_height="wrap_content"  
           android:ems="15"  
           android:focusable="false"  
           android:hint="Upload ID Proof"  
           android:imeOptions="actionNext"  
           android:inputType="none" />  
       </android.support.design.widget.TextInputLayout>  
       <ImageView  
         android:id="@+id/PhotoIDImageView"  
         android:layout_width="40dp"  
         android:layout_height="30dp"  
         android:layout_gravity="center"  
         android:src="@drawable/cam" />  
     </LinearLayout>  
     <ImageView  
       android:id="@+id/PhotoIDImageView1"  
       android:layout_width="150dp"  
       android:layout_height="150dp"  
       android:layout_gravity="center" />  
     <Button  
       android:id="@+id/Upload"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:text="Upload"/>  
   </LinearLayout>  
 </android.support.constraint.ConstraintLayout>