Wednesday, November 8, 2017

Insert Image From Android To Database (PHP + MySQL)

This article will show a simple tutorial about how to insert image from android to database. Insert image from android to database possible achieve by creating local database using PHP and MySQL.

So this tutorial using two projects, 1 PHP project and the other one is Android project. Don't forget to create your database to store the image that received from Android.

Image will be send from android by send its json to server. In php project, we also create a file that handle json from mobile (android).

Scenario 


We will save the file of image in the directory inside the php project. In database we just store the path of the image from php project.

For example
  • Users choose image obama.jpg from their android
  • In PHP project, there is a directory named imagefromandroid.
  • In database, just store its path, so it's become : imagefromandroid/obama.jpg.

Create Database


In this project i just create simple database, only one table. Please adjust your project and your database.

Database

PHP Project


Create a directory that used to save the file of image that received from android. Take a look at the following image

Directory

I above figure, i create a directory where image from mobile android will stored name imagefromandroid. Also, we will use two php classes, Connection.php and insertImageFromMobile.php.

Connection.php


This file used to connect your PHP Project to your database. The code look like the follows :

<?php
/**
* Created by PhpStorm.
* User: putuguna
* Date: 2/13/2017
* Time: 2:55 PM
*/
class Connection{
function getConnection(){
$host = "localhost"; //your host
$user = "root"; // your database username
$password = ""; // your database password
$dbname = "insertimage"; //your database name
try{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}catch (PDOException $e){
echo "Error while connecting database : " . $e->getMessage();
}
}
}
view raw Connection.php hosted with ❤ by GitHub
InsertImageFromMobile.java


This class used to handle data that received from mobile in json form. The code is look like the follows :

<?php
//
/**
* Created by PhpStorm.
* User: putuguna
* Date: 2/13/2017
* Time: 3:07 PM
*/
require_once("Connection.php");
class InsertImageFromMobile
{
function insertImage()
{
$connection = new Connection();
$conn = $connection->getConnection();
$target_dir = "imagefromandroid/";
$target_file_name = $target_dir . basename($_FILES["file"]["name"]);
$response = array();
// check the file is image or not
if (isset($_FILES["file"])) {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name)) {
$imagePath = $target_file_name;
try {
$sql = "INSERT INTO gallery (image) VALUES ('$imagePath')";
$myImage = $conn->prepare($sql);
$myImage->execute();
} catch (PDOException $e) {
$e->getMessage();
}
$success = true;
$message = "Successfully Uploaded";
} else {
$success = false;
$message = "Error while uploading";
}
} else {
$success = false;
$message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
}
}
$insertImage = new InsertImageFromMobile();
$insertImage->insertImage();
?>

Android Project


There are several classes and xml files that we create in order to able to send image to the server or database.

LoggingInterceptors.java


This class created for handle response of retrofit. In other word, we able to see request process of retrofit to the endpoint.

package com.putuguna.insertimageandroidtophp;
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
/**
* Created by putuguna on 8/5/2017.
*/
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
String requestLog = String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers());
//YLog.d(String.format("Sending request %s on %s%n%s",
// request.url(), chain.connection(), request.headers()));
if (request.method().compareToIgnoreCase("post") == 0) {
requestLog = "\n" + requestLog + "\n" + bodyToString(request);
}
Log.d("TAG", "request" + "\n" + requestLog);
Response response = chain.proceed(request);
long t2 = System.nanoTime();
String responseLog = String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers());
String bodyString = response.body().string();
Log.d("TAG", "response" + "\n" + responseLog + "\n" + bodyString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), bodyString))
.build();
}
public static String bodyToString(final Request request) {
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
return "did not work";
}
}
}

ResultModel.java


This class will handle response message of request. The response message that will shown by this class are success or failed.


package com.putuguna.insertimageandroidtophp;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by putuguna on 8/5/2017.
*/
public class ResultModel {
@SerializedName("success")
boolean success;
@SerializedName("message")
String message;
String getMessage() {
return message;
}
boolean getSuccess() {
return success;
}
}

ApiService.java


This class is an interface. In this class will declare endpoint of BASE URL.


package com.putuguna.insertimageandroidtophp;
/**
* Created by putuguna on 8/5/2017.
*/
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface ApiService {
@Multipart
@POST("InsertImageFromMobile.php")
Call<ResultModel> uploadImagee(@Part MultipartBody.Part file, @Part("file") RequestBody name);
}
view raw ApiService.java hosted with ❤ by GitHub

ApiClient.java



This class contains the BASE URL that used in this project. And also in this class contains initialized of the retrofit
package com.putuguna.insertimageandroidtophp;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by putuguna on 8/5/2017.
*/
public class ApiClient {
public static final String URL = "http://192.168.43.147/InsertImage/";
public static Retrofit RETROFIT = null;
public ApiClient() {
}
public static Retrofit getClient(){
if(RETROFIT==null){
//
// Gson gson = new GsonBuilder()
// .setLenient()
// .create();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
RETROFIT = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return RETROFIT;
}
}
view raw ApiClient.java hosted with ❤ by GitHub

MainActivity.java


All class or method that used to send image to the server will called in this class. Full code of MainActivity :

package com.putuguna.insertimageandroidtophp;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Image;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.io.File;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pl.aprilapps.easyphotopicker.DefaultCallback;
import pl.aprilapps.easyphotopicker.EasyImage;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CODE_CAMERA = 0012;
public static final int REQUEST_CODE_GALLERY = 0013;
private String [] items = {"Camera","Gallery"};
private ImageView ivImage;
private Button btnBrowse;
private Button btnUpload;
private TextView tvPath;
private String imagePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivImage = (ImageView) findViewById(R.id.imageview);
btnBrowse = (Button) findViewById(R.id.btn_browse_image);
btnUpload = (Button) findViewById(R.id.btn_upload);
tvPath = (TextView) findViewById(R.id.textview_path);
btnBrowse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
uploadImage();
}
});
}
private void uploadImage(){
File file = new File(imagePath);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("loading...");
progressDialog.show();
ApiService apiService = ApiClient.getClient().create(ApiService.class);
Call<ResultModel> call = apiService.uploadImagee(fileToUpload,filename);
call.enqueue(new Callback<ResultModel>() {
@Override
public void onResponse(Call<ResultModel> call, Response<ResultModel> response) {
Toast.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
System.out.println("ERROR : " + response.body().getMessage());
}
@Override
public void onFailure(Call<ResultModel> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
System.out.println("ERROR : " + t.getMessage());
progressDialog.dismiss();
}
});
}
private void openImage(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select image");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if(items[i].equals("Camera")){
EasyImage.openCamera(MainActivity.this, REQUEST_CODE_CAMERA);
}else if(items[i].equals("Gallery")){
EasyImage.openGallery(MainActivity.this, REQUEST_CODE_GALLERY);
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
@Override
public void onImagesPicked( List<File> imageFiles, EasyImage.ImageSource source, int type) {
switch (type){
case REQUEST_CODE_CAMERA:
imagePath = imageFiles.get(0).getAbsolutePath();
Glide.with(MainActivity.this)
.load(imageFiles.get(0))
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(ivImage);
break;
case REQUEST_CODE_GALLERY:
imagePath = imageFiles.get(0).getAbsolutePath();
Glide.with(MainActivity.this)
.load(imageFiles.get(0))
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(ivImage);
break;
}
}
});
}
}

Okay, that's all. Hope it helps you to learn how to insert image from android to database.

Related Posts

1 komentar so far

hi sir, where did you put LoggingInterceptor?


EmoticonEmoticon

:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:o
:>)
(o)
:p
:-?
(p)
:-s
8-)
:-t
:-b
b-(
(y)
x-)
(h)