Capture Image and Upload to Server in Android

How to Take a photo from camera and upload online and salve image path into MySQL database with prototype name project with Runtime Camera permission.

In this tutorial we would going to create an android application which would capture epitome from android mobile phone photographic camera and show that prototype inside ImageView. After capturing nosotros would gear up image name into EditText and upload image online to our hosting server. While uploading we would likewise show ProgressBar dialog on app screen. The paradigm would store on our server inside a folder created past myself and the whole prototype path salve into MySQL database forth with image proper name. We are using PHP script to receive and shop paradigm on server. And then hither is the complete step past pace tutorial for Android Capture Image From Photographic camera Upload to Server Using PHP MySQL.

Contents in this projection Android Capture Prototype From Camera Upload to Server Using PHP MySQL :-

  1. Create Database including table on your server.
  2. Create folder named asimages on your server.
  3. Create PHP Script to receive send image from android phone.
  4. Beginning a fresh android app development project.
  5. Add together cyberspace and camera permission within the project Manifest.xml file.
  6. Offset coding.

1. Create Database including tabular array on your server :

Create a fresh database on your server and within that database create a fresh table which volition used to shop epitome name and image path inside MySQL database similar i did in below screenshot.

2. Create folder named equallyimages on your server :

Later creating table we have to create a binder on our hosting server which will used to store images.

3. Create PHP Script to receive transport image from android phone :

At present nosotros would have to create 2 php files first i is capture_img_upload_to_server.php file and DatabaseConfig.php file and upload that file into our server. These file volition used to receive and store image details, image itself, image proper name on MySQL database.

Code for capture_img_upload_to_server.php file.

<?php  include 'DatabaseConfig.php';  // Create connection $conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);    if($_SERVER['REQUEST_METHOD'] == 'POST')  {  $DefaultId = 0;    $ImageData = $_POST['image_path'];    $ImageName = $_POST['image_name'];   $GetOldIdSQL ="SELECT id FROM ImageToServerTable Gild Past id ASC";    $Query = mysqli_query($conn,$GetOldIdSQL);    while($row = mysqli_fetch_array($Query)){    $DefaultId = $row['id'];  }    $ImagePath = "images/$DefaultId.png";    $ServerURL = "https://androidjsonblog.000webhostapp.com/$ImagePath";    $InsertSQL = "insert into ImageToServerTable (image_path,image_name) values ('$ServerURL','$ImageName')";    if(mysqli_query($conn, $InsertSQL)){   file_put_contents($ImagePath,base64_decode($ImageData));   echo "Your Image Has Been Uploaded.";  }    mysqli_close($conn);  }else{  echo "Not Uploaded";  }  ?>        

Code for DatabaseConfig.php file.

<?php  //Ascertain your host hither. $HostName = "localhost";  //Define your database username here. $HostUser = "id632449_androidjson";  //Define your database password hither. $HostPass = "kdfjdfdskljomew9ry3873";  //Define your database name here. $DatabaseName = "id632449_androidjson";  ?>

5. Add internet and camera permission inside the project Manifest.xml file :

Open your project'south AndroidManifest.xml file and add together camera permission and internet permission inside it.

<uses-permission android:name="android.permission.Camera" /> <uses-permission android:name="android.permission.INTERNET" />

 six. Start coding For Project :-

Lawmaking for MainActivity.java file.

package com.androidjson.captureimageupload_androidjsoncom; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.net.HttpURLConnection; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.app.ProgressDialog; import android.os.AsyncTask; import android.widget.EditText; import android.net.Uri; import java.io.InputStreamReader; import coffee.io.OutputStream; import javax.cyberspace.ssl.HttpsURLConnection; import coffee.io.BufferedWriter; import java.util.Map; import java.io.ByteArrayOutputStream; import coffee.io.IOException; import java.util.HashMap; import java.io.OutputStreamWriter; import java.net.URL; import android.provider.MediaStore; import coffee.io.BufferedReader; import java.net.URLEncoder; import java.io.UnsupportedEncodingException; import android.util.Base64;  public grade MainActivity extends AppCompatActivity {      Button CaptureImageFromCamera,UploadImageToServer;      ImageView ImageViewHolder;      EditText imageName;      ProgressDialog progressDialog ;      Intent intent ;      public  static final int RequestPermissionCode  = one ;      Bitmap bitmap;      boolean check = true;      String GetImageNameFromEditText;      Cord ImageNameFieldOnServer = "image_name" ;      Cord ImagePathFieldOnServer = "image_path" ;      Cord ImageUploadPathOnSever ="https://androidjsonblog.000webhostapp.com/capture_img_upload_to_server.php" ;       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          CaptureImageFromCamera = (Push button)findViewById(R.id.push);         ImageViewHolder = (ImageView)findViewById(R.id.imageView);         UploadImageToServer = (Push button) findViewById(R.id.button2);         imageName = (EditText)findViewById(R.id.editText);          EnableRuntimePermissionToAccessCamera();          CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                  intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);                  startActivityForResult(intent, 7);              }         });          UploadImageToServer.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                  GetImageNameFromEditText = imageName.getText().toString();                  ImageUploadToServerFunction();              }         });     }  // Star activeness for issue method to Set up captured epitome on epitome view after click.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {          super.onActivityResult(requestCode, resultCode, data);          if (requestCode == vii && resultCode == RESULT_OK && information != null && data.getData() != null) {              Uri uri = data.getData();              try {                  // Adding captured image in bitmap.                 bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);                  // adding captured image in imageview.                 ImageViewHolder.setImageBitmap(bitmap);              } catch (IOException east) {                  due east.printStackTrace();             }         }      }      // Requesting runtime permission to admission camera.     public void EnableRuntimePermissionToAccessCamera(){          if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,                 Manifest.permission.Camera))         {              // Printing toast message later enabling runtime permission.             Toast.makeText(MainActivity.this,"CAMERA permission allows usa to Access Photographic camera app", Toast.LENGTH_LONG).show();          } else {              ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.Photographic camera}, RequestPermissionCode);          }     }      // Upload captured image online on server office.     public void ImageUploadToServerFunction(){          ByteArrayOutputStream byteArrayOutputStreamObject ;          byteArrayOutputStreamObject = new ByteArrayOutputStream();          // Converting bitmap paradigm to jpeg format, so by default image will upload in jpeg format.         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStreamObject);          byte[] byteArrayVar = byteArrayOutputStreamObject.toByteArray();          last String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);          class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {              @Override             protected void onPreExecute() {                  super.onPreExecute();                  // Showing progress dialog at prototype upload time.                 progressDialog = ProgressDialog.testify(MainActivity.this,"Epitome is Uploading","Please Expect",false,false);             }              @Override             protected void onPostExecute(Cord string1) {                  super.onPostExecute(string1);                  // Dismiss the progress dialog after done uploading.                 progressDialog.dismiss();                  // Printing uploading success message coming from server on android app.                 Toast.makeText(MainActivity.this,string1,Toast.LENGTH_LONG).show();                  // Setting image every bit transparent after done uploading.                 ImageViewHolder.setImageResource(android.R.color.transparent);               }              @Override             protected String doInBackground(Void... params) {                  ImageProcessClass imageProcessClass = new ImageProcessClass();                  HashMap<String,String> HashMapParams = new HashMap<Cord,Cord>();                  HashMapParams.put(ImageNameFieldOnServer, GetImageNameFromEditText);                  HashMapParams.put(ImagePathFieldOnServer, ConvertImage);                  String FinalData = imageProcessClass.ImageHttpRequest(ImageUploadPathOnSever, HashMapParams);                  return FinalData;             }         }         AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();          AsyncTaskUploadClassOBJ.execute();     }      public grade ImageProcessClass{          public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) {              StringBuilder stringBuilder = new StringBuilder();              effort {                  URL url;                 HttpURLConnection httpURLConnectionObject ;                 OutputStream OutPutStream;                 BufferedWriter bufferedWriterObject ;                 BufferedReader bufferedReaderObject ;                 int RC ;                  url = new URL(requestURL);                  httpURLConnectionObject = (HttpURLConnection) url.openConnection();                  httpURLConnectionObject.setReadTimeout(19000);                  httpURLConnectionObject.setConnectTimeout(19000);                  httpURLConnectionObject.setRequestMethod("POST");                  httpURLConnectionObject.setDoInput(true);                  httpURLConnectionObject.setDoOutput(true);                  OutPutStream = httpURLConnectionObject.getOutputStream();                  bufferedWriterObject = new BufferedWriter(                          new OutputStreamWriter(OutPutStream, "UTF-8"));                  bufferedWriterObject.write(bufferedWriterDataFN(PData));                  bufferedWriterObject.affluent();                  bufferedWriterObject.shut();                  OutPutStream.close();                  RC = httpURLConnectionObject.getResponseCode();                  if (RC == HttpsURLConnection.HTTP_OK) {                      bufferedReaderObject = new BufferedReader(new InputStreamReader(httpURLConnectionObject.getInputStream()));                      stringBuilder = new StringBuilder();                      String RC2;                      while ((RC2 = bufferedReaderObject.readLine()) != goose egg){                          stringBuilder.append(RC2);                     }                 }              } catch (Exception e) {                 east.printStackTrace();             }             return stringBuilder.toString();         }          private Cord bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {              StringBuilder stringBuilderObject;              stringBuilderObject = new StringBuilder();              for (Map.Entry<Cord, String> KEY : HashMapParams.entrySet()) {                  if (bank check)                      check = false;                 else                     stringBuilderObject.append("&");                  stringBuilderObject.suspend(URLEncoder.encode(KEY.getKey(), "UTF-8"));                  stringBuilderObject.append("=");                  stringBuilderObject.append(URLEncoder.encode(Central.getValue(), "UTF-8"));             }              render stringBuilderObject.toString();         }      }      @Override     public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {          switch (RC) {              case RequestPermissionCode:                  if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {                      Toast.makeText(MainActivity.this,"Permission Granted, Now your awarding tin admission Camera.", Toast.LENGTH_LONG).testify();                  } else {                      Toast.makeText(MainActivity.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();                  }                 break;         }     }  }

Lawmaking for activity_main.xml layout file.

<?xml version="ane.0" encoding="utf-8"?> <RelativeLayout     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="com.androidjson.captureimageupload_androidjsoncom.MainActivity">      <ImageView         android:layout_width="fill_parent"         android:layout_height="270dp"         android:id="@+id/imageView"         android:layout_alignParentTop="true"         android:layout_alignParentLeft="truthful"         android:layout_alignParentStart="true" />      <Button         android:text="Click hither to capture image using camera"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:id="@+id/push button"         android:layout_below="@+id/imageView"/>      <EditText         android:id="@+id/editText"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:layout_below="@+id/push"         android:layout_centerHorizontal="true"         android:ems="ten"         android:inputType="textPersonName"         android:hint="Enter Image Proper name"         android:gravity="eye"         android:layout_marginTop="10dp"/>      <Button         android:id="@+id/button2"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:text="Upload Captured Image On Server"         android:layout_below="@+id/editText"         android:layout_alignParentLeft="truthful"         android:layout_alignParentStart="true" />  </RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-viii"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     parcel="com.androidjson.captureimageupload_androidjsoncom">      <uses-permission android:name="android.permission.CAMERA" />     <uses-permission android:name="android.permission.Cyberspace" />      <awarding         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:theme="@style/AppTheme">         <activeness android:proper name=".MainActivity">             <intent-filter>                 <action android:name="android.intent.activity.Main" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </action>     </application>  </manifest>

Screenshots:-

Android Capture Image From Camera Upload to Server Using PHP MySQL

Download Code

garlandwithoped.blogspot.com

Source: https://androidjson.com/capture-image-camera-upload-server/

0 Response to "Capture Image and Upload to Server in Android"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel