mobile camera images upload to a server

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

In this tutorial we would going to create an android application which would capture image from android mobile phone camera and testify that image inside ImageView. After capturing we would set image name into EditText and upload image online to our hosting server. While uploading we would also show ProgressBar dialog on app screen. The paradigm would store on our server inside a binder created by myself and the whole image path save into MySQL database along with image name. We are using PHP script to receive and store prototype on server. So here is the consummate stride by stride tutorial for Android Capture Paradigm From Camera Upload to Server Using PHP MySQL.

Contents in this project 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 ship epitome from android phone.
  4. Start a fresh android app development project.
  5. Add cyberspace and camera permission inside the project Manifest.xml file.
  6. First coding.

1. Create Database including table on your server :

Create a fresh database on your server and inside that database create a fresh table which will used to store paradigm name and image path inside MySQL database like i did in beneath screenshot.

2. Create folder named asimages on your server :

After creating table nosotros accept to create a binder on our hosting server which will used to store images.

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

Now we would have to create 2 php files first one is capture_img_upload_to_server.php file and DatabaseConfig.php file and upload that file into our server. These file will used to receive and store paradigm details, prototype itself, image 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 Guild By 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{  repeat "Not Uploaded";  }  ?>        

Code for DatabaseConfig.php file.

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

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

Open your projection's AndroidManifest.xml file and add photographic camera permission and cyberspace permission within it.

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

 6. Start coding For Projection :-

Code 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.Push button; import android.widget.ImageView; import android.widget.Toast; import coffee.internet.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 java.io.OutputStream; import javax.internet.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.cyberspace.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  = 1 ;      Bitmap bitmap;      boolean bank check = true;      Cord GetImageNameFromEditText;      String ImageNameFieldOnServer = "image_name" ;      Cord ImagePathFieldOnServer = "image_path" ;      Cord ImageUploadPathOnSever ="https://androidjsonblog.000webhostapp.com/capture_img_upload_to_server.php" ;       @Override     protected void onCreate(Parcel savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          CaptureImageFromCamera = (Button)findViewById(R.id.button);         ImageViewHolder = (ImageView)findViewById(R.id.imageView);         UploadImageToServer = (Push) 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, seven);              }         });          UploadImageToServer.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                  GetImageNameFromEditText = imageName.getText().toString();                  ImageUploadToServerFunction();              }         });     }  // Star activity for effect method to Set captured prototype on epitome view after click.     protected void onActivityResult(int requestCode, int resultCode, Intent information) {          super.onActivityResult(requestCode, resultCode, data);          if (requestCode == 7 && resultCode == RESULT_OK && data != zero && data.getData() != cipher) {              Uri uri = information.getData();              attempt {                  // Adding captured image in bitmap.                 bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);                  // calculation captured image in imageview.                 ImageViewHolder.setImageBitmap(bitmap);              } catch (IOException due east) {                  e.printStackTrace();             }         }      }      // Requesting runtime permission to access camera.     public void EnableRuntimePermissionToAccessCamera(){          if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,                 Manifest.permission.Photographic camera))         {              // Printing toast message after enabling runtime permission.             Toast.makeText(MainActivity.this,"CAMERA permission allows the states to Access Camera app", Toast.LENGTH_LONG).show();          } else {              ActivityCompat.requestPermissions(MainActivity.this,new Cord[]{Manifest.permission.Photographic camera}, RequestPermissionCode);          }     }      // Upload captured image online on server function.     public void ImageUploadToServerFunction(){          ByteArrayOutputStream byteArrayOutputStreamObject ;          byteArrayOutputStreamObject = new ByteArrayOutputStream();          // Converting bitmap image to jpeg format, so by default image will upload in jpeg format.         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStreamObject);          byte[] byteArrayVar = byteArrayOutputStreamObject.toByteArray();          terminal String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);          form AsyncTaskUploadClass extends AsyncTask<Void,Void,Cord> {              @Override             protected void onPreExecute() {                  super.onPreExecute();                  // Showing progress dialog at image upload time.                 progressDialog = ProgressDialog.evidence(MainActivity.this,"Image is Uploading","Please Expect",false,false);             }              @Override             protected void onPostExecute(String 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 epitome as transparent after washed uploading.                 ImageViewHolder.setImageResource(android.R.color.transparent);               }              @Override             protected String doInBackground(Void... params) {                  ImageProcessClass imageProcessClass = new ImageProcessClass();                  HashMap<String,String> HashMapParams = new HashMap<String,Cord>();                  HashMapParams.put(ImageNameFieldOnServer, GetImageNameFromEditText);                  HashMapParams.put(ImagePathFieldOnServer, ConvertImage);                  String FinalData = imageProcessClass.ImageHttpRequest(ImageUploadPathOnSever, HashMapParams);                  return FinalData;             }         }         AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();          AsyncTaskUploadClassOBJ.execute();     }      public class ImageProcessClass{          public String ImageHttpRequest(String requestURL,HashMap<Cord, 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(truthful);                  httpURLConnectionObject.setDoOutput(truthful);                  OutPutStream = httpURLConnectionObject.getOutputStream();                  bufferedWriterObject = new BufferedWriter(                          new OutputStreamWriter(OutPutStream, "UTF-8"));                  bufferedWriterObject.write(bufferedWriterDataFN(PData));                  bufferedWriterObject.flush();                  bufferedWriterObject.close();                  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()) != null){                          stringBuilder.append(RC2);                     }                 }              } catch (Exception e) {                 e.printStackTrace();             }             return stringBuilder.toString();         }          private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {              StringBuilder stringBuilderObject;              stringBuilderObject = new StringBuilder();              for (Map.Entry<String, String> Central : HashMapParams.entrySet()) {                  if (check)                      check = false;                 else                     stringBuilderObject.append("&");                  stringBuilderObject.append(URLEncoder.encode(Primal.getKey(), "UTF-viii"));                  stringBuilderObject.suspend("=");                  stringBuilderObject.append(URLEncoder.encode(Primal.getValue(), "UTF-8"));             }              return 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 application tin access CAMERA.", Toast.LENGTH_LONG).evidence();                  } else {                      Toast.makeText(MainActivity.this,"Permission Canceled, Now your application cannot access Photographic camera.", Toast.LENGTH_LONG).bear witness();                  }                 interruption;         }     }  }

Code for activity_main.xml layout file.

<?xml version="i.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 here to capture image using camera"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:id="@+id/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/button"         android:layout_centerHorizontal="truthful"         android:ems="10"         android:inputType="textPersonName"         android:hint="Enter Image Name"         android:gravity="center"         android:layout_marginTop="10dp"/>      <Push 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="true"         android:layout_alignParentStart="true" />  </RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.androidjson.captureimageupload_androidjsoncom">      <uses-permission android:proper name="android.permission.Photographic camera" />     <uses-permission android:proper name="android.permission.INTERNET" />      <application         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:theme="@mode/AppTheme">         <activity android:name=".MainActivity">             <intent-filter>                 <activity android:proper name="android.intent.action.Master" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application>  </manifest>

Screenshots:-

Android Capture Image From Camera Upload to Server Using PHP MySQL

Download Code

flemingpontliatich.blogspot.com

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

0 Response to "mobile camera images upload to a server"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel