Hello friends welcome to our new Android Upload Image Using PHP MySQL Tutorial. I already published tutorials about how to upload image to server from android. But in last tutorial I stored android images to MySQL database. Now in this tutorial we won’t store image to MySQL database instead we will save our image inside a directory. So in this tutorial we will store image to a directory and the path of the image to our mysql database. And we will also fetch the stored image to our Android App. So lets begin.
Android Upload Image Using PHP MySQL Video
You can check out this video before moving ahead. This will show you that what you will be creating with this tutorial.
Making Your Server Ready for Image Upload
- So we also need to create a database table this time. But this time we will store the path to the image in database. Create the following database
- Now, in your server create a new directory. I created PhotoUpload
- Inside the directory you need a script to connect to your database. So create a script name dbConnect.php and write the following code
1 2 3 4 5 6 7 8 9 |
<?php define('HOST','mysql.hostinger.in'); define('USER','u502452270_andro'); define('PASS','belal_123'); define('DB','u502452270_andro'); $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect'); |
- Now you need one more script that will handle the photo upload. So I created a script named upload.php with the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php if($_SERVER['REQUEST_METHOD']=='POST'){ $image = $_POST['image']; require_once('dbConnect.php'); $sql ="SELECT id FROM photos ORDER BY id ASC"; $res = mysqli_query($con,$sql); $id = 0; while($row = mysqli_fetch_array($res)){ $id = $row['id']; } $path = "uploads/$id.png"; $actualpath = "http://simplifiedcoding.16mb.com/PhotoUpload/$path"; $sql = "INSERT INTO photos (image) VALUES ('$actualpath')"; if(mysqli_query($con,$sql)){ file_put_contents($path,base64_decode($image)); echo "Successfully Uploaded"; } mysqli_close($con); }else{ echo "Error"; } |
- Now the above script will handle uploads. It will store the images sent to a directory name uploads. So you also need to create a directory name uploads.
- The above script will store the path to the images inside the MySQL database through which we will fetch all the images.
- So we need one more image which will give the urls of all the images. For getting the urls we will use JSON.
- Create a new script named getAllImages.php and write the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php require_once('dbConnect.php'); $sql = "select image from photos"; $res = mysqli_query($con,$sql); $result = array(); while($row = mysqli_fetch_array($res)){ array_push($result,array('url'=>$row['image'])); } echo json_encode(array("result"=>$result)); mysqli_close($con); |
- Now our server part is over. You can see below the snapshot of my server’s directory.
- I have the path of my upload.php and getAllImages.php script.
- upload.php ->Â http://simplifiedcoding.16mb.com/PhotoUpload/upload.php
- getAllImages.php ->Â http://simplifiedcoding.16mb.com/PhotoUpload/getAllImages.php
Creating Android Upload Image Using PHP MySQL Project
- Open Android Studio and Create a New Android Project
- This part is same as we did before in how to upload image from android
- You need to create the following layout
- The following xml code will create the above layout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/string_choose_file" android:id="@+id/buttonChoose" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/imageView" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/string_upload_image" android:id="@+id/buttonUpload" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/string_view_image" android:id="@+id/buttonViewImage" /> </LinearLayout> |
- Create a new java class to handler our http request. I created RequestHandler.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
package net.simplifiedcoding.imageuploadsample; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; /** * Created by Belal on 8/19/2015. */ public class RequestHandler { public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) { URL url; StringBuilder sb = new StringBuilder(); try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); String response; while ((response = br.readLine()) != null){ sb.append(response); } } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } } |
- Now in the MainActivity.java write the following code to make the upload work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
package net.simplifiedcoding.imageuploadsample; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Base64; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final String UPLOAD_URL = "http://simplifiedcoding.16mb.com/PhotoUpload/upload.php"; public static final String UPLOAD_KEY = "image"; private int PICK_IMAGE_REQUEST = 1; private Button buttonChoose; private Button buttonUpload; private Button buttonView; private ImageView imageView; private Bitmap bitmap; private Uri filePath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonChoose = (Button) findViewById(R.id.buttonChoose); buttonUpload = (Button) findViewById(R.id.buttonUpload); buttonView = (Button) findViewById(R.id.buttonViewImage); imageView = (ImageView) findViewById(R.id.imageView); buttonChoose.setOnClickListener(this); buttonUpload.setOnClickListener(this); buttonView.setOnClickListener(this); } private void showFileChooser() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { filePath = data.getData(); try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } public String getStringImage(Bitmap bmp){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); return encodedImage; } private void uploadImage(){ class UploadImage extends AsyncTask<Bitmap,Void,String>{ ProgressDialog loading; RequestHandler rh = new RequestHandler(); @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(MainActivity.this, "Uploading...", null,true,true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(Bitmap... params) { Bitmap bitmap = params[0]; String uploadImage = getStringImage(bitmap); HashMap<String,String> data = new HashMap<>(); data.put(UPLOAD_KEY, uploadImage); String result = rh.sendPostRequest(UPLOAD_URL,data); return result; } } UploadImage ui = new UploadImage(); ui.execute(bitmap); } @Override public void onClick(View v) { if (v == buttonChoose) { showFileChooser(); } if(v == buttonUpload){ uploadImage(); } if(v == buttonView){ viewImage(); } } private void viewImage() { startActivity(new Intent(this, ImageListView.class)); } } |
- Your app will now give you some error because we have not created new activity named ImageListView.class. You can comment this line for now.
- Now add Internet permission to your manifest. Your upload image will work at this point.
- Try running your app your image upload should work.
- Now the lets move to the next part which is downloading uploaded images.
Showing Uploaded Images to a ListView in Android
The process I will be following here is good when you have to load few images. Because here we will be downloading all the images at once. And if you have 100s or 1000s images to show up on ListView, you should not follow this. So to make your list efficient check this tutorial here
- Uncomment your line which were causing error before. Now to remove this error we need to create a new Activity.
- Create a blank activity. I just created ImageListView.
- Now when we will click the View Image button this activity should open.
- In this activity we will create a ListView. So come to the respective layout of this activity. (In my case it is activity_image_list_view.xml
- We need to create the following layout
- You can use the following xml code for creating above layout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="net.simplifiedcoding.imageuploadsample.ImageListView"> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/listView" /> </LinearLayout> |
- We have to create a Custom List View for so we will create a new xml resource file for our Custom List View.
- I created image_list_view.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/imageDownloaded" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/abc_ic_menu_copy_mtrl_am_alpha"/> <TextView android:id="@+id/textViewURL" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> |
- Now create a new class named CustomList for our Custom List View.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package net.simplifiedcoding.imageuploadsample; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; /** * Created by Belal on 7/22/2015. */ public class CustomList extends ArrayAdapter<String> { private String[] urls; private Bitmap[] bitmaps; private Activity context; public CustomList(Activity context, String[] urls, Bitmap[] bitmaps) { super(context, R.layout.image_list_view, urls); this.context = context; this.urls= urls; this.bitmaps= bitmaps; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View listViewItem = inflater.inflate(R.layout.image_list_view, null, true); TextView textViewURL = (TextView) listViewItem.findViewById(R.id.textViewURL); ImageView image = (ImageView) listViewItem.findViewById(R.id.imageDownloaded); textViewURL.setText(urls[position]); image.setImageBitmap(Bitmap.createScaledBitmap(bitmaps[position],100,50,false)); return listViewItem; } } |
- Now we need to fetch all the Bitmaps from server. So for this we will create a new class. I created GetAlImages.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
package net.simplifiedcoding.imageuploadsample; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; /** * Created by Belal on 9/19/2015. */ public class GetAlImages { public static String[] imageURLs; public static Bitmap[] bitmaps; public static final String JSON_ARRAY="result"; public static final String IMAGE_URL = "url"; private String json; private JSONArray urls; public GetAlImages(String json){ this.json = json; try { JSONObject jsonObject = new JSONObject(json); urls = jsonObject.getJSONArray(JSON_ARRAY); } catch (JSONException e) { e.printStackTrace(); } } private Bitmap getImage(JSONObject jo){ URL url = null; Bitmap image = null; try { url = new URL(jo.getString(IMAGE_URL)); image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return image; } public void getAllImages() throws JSONException { bitmaps = new Bitmap[urls.length()]; imageURLs = new String[urls.length()]; for(int i=0;i<urls.length();i++){ imageURLs[i] = urls.getJSONObject(i).getString(IMAGE_URL); JSONObject jsonObject = urls.getJSONObject(i); bitmaps[i]=getImage(jsonObject); } } } |
- We will pass the json string having all the urls of our images to the constructor of this class.
- We will get the json string having all the urls from our getAllImages.php script.
- Now come to ImageListView.java class and write the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
package net.simplifiedcoding.imageuploadsample; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Bitmap; import android.media.Image; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import org.json.JSONException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class ImageListView extends AppCompatActivity implements AdapterView.OnItemClickListener { private ListView listView; public static final String GET_IMAGE_URL="http://simplifiedcoding.16mb.com/PhotoUpload/getAllImages.php"; public GetAlImages getAlImages; public static final String BITMAP_ID = "BITMAP_ID"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_list_view); listView = (ListView) findViewById(R.id.listView); listView.setOnItemClickListener(this); getURLs(); } private void getImages(){ class GetImages extends AsyncTask<Void,Void,Void>{ ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(ImageListView.this,"Downloading images...","Please wait...",false,false); } @Override protected void onPostExecute(Void v) { super.onPostExecute(v); loading.dismiss(); //Toast.makeText(ImageListView.this,"Success",Toast.LENGTH_LONG).show(); CustomList customList = new CustomList(ImageListView.this,GetAlImages.imageURLs,GetAlImages.bitmaps); listView.setAdapter(customList); } @Override protected Void doInBackground(Void... voids) { try { getAlImages.getAllImages(); } catch (JSONException e) { e.printStackTrace(); } return null; } } GetImages getImages = new GetImages(); getImages.execute(); } private void getURLs() { class GetURLs extends AsyncTask<String,Void,String>{ ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(ImageListView.this,"Loading...","Please Wait...",true,true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); getAlImages = new GetAlImages(s); getImages(); } @Override protected String doInBackground(String... strings) { BufferedReader bufferedReader = null; try { URL url = new URL(strings[0]); HttpURLConnection con = (HttpURLConnection) url.openConnection(); StringBuilder sb = new StringBuilder(); bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream())); String json; while((json = bufferedReader.readLine())!= null){ sb.append(json+"\n"); } return sb.toString().trim(); }catch(Exception e){ return null; } } } GetURLs gu = new GetURLs(); gu.execute(GET_IMAGE_URL); } @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent intent = new Intent(this, ViewFullImage.class); intent.putExtra(BITMAP_ID,i); startActivity(intent); } } |
- Now we will create a new activity to see the full size image. I created ViewFullImage.java.
- We will create a ImageView to the layout file of this activity.
- The xml code for the above layout is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="net.simplifiedcoding.imageuploadsample.ViewFullImage"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/imageViewFull" /> </RelativeLayout> |
- Inside your java class for this layout write the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package net.simplifiedcoding.imageuploadsample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; public class ViewFullImage extends AppCompatActivity { private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_full_image); Intent intent = getIntent(); int i = intent.getIntExtra(ImageListView.BITMAP_ID,0); imageView = (ImageView) findViewById(R.id.imageViewFull); imageView.setImageBitmap(GetAlImages.bitmaps[i]); } } |
- Now thats it. If you want the source code of this project you can download from here
[easy_media_download url=”https://dl.dropboxusercontent.com/s/697f4y7ah9x0wm0/android-upload-image-to-server-using-php-mysql.zip?dl=0″ text=”Download Source”]
So thats it for this Android Upload Image Using PHP MySQL Tutorial friends. If you are having confusions please leave you comments below.