Code Android pour envoyer une image vers un serveur distant via un web service (PHP)
Dans ce tutoriel on va apprendre comment prendre une image par une application android et l'envoyer à un serveur distant.
Tout d'abord il faut créer un web service avec le langage PHP.
Web service php pour l'envoie de l'image au serveur
//On suppose que ce fichier porte le nom de image.php
Par la suite il faut créer un nouveau projet android. Pour l'interface xml il faut mettre une ImageView et deux boutons; l'un pour prendre l'image et l'autre pour l'envoyer au serveur.
<?php header('Access-Control-Allow-Origin: *'); error_reporting(E_ALL); if(isset($_POST['ImageName'])){ $imgname = $_POST['ImageName']; $imsrc = str_replace(' ','+',$_POST['base64']); $imsrc = base64_decode($imsrc); $fp = fopen($imgname, 'w'); fwrite($fp, $imsrc); if(fclose($fp)){ echo "Image uploaded"; }else{ echo "Error uploading image"; } } ?>
Code du fichier xml qui représente le layout de base
<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=".MainActivity"> <ImageView
android:id="@+id/Imageprev"
android:layout_width="match_parent"
android:layout_height="400dp" /> <Button android:id="@+id/cpic"
android:text="prendre Image"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/Imageprev" /> <Button android:id="@+id/up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Envoie Image"
android:layout_below="@+id/cpic"
android:layout_centerInParent="true" /> </RelativeLayout>
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Finalement il nous reste la partie JAVA.
Tout d'abord il faut créer une nouvelle classe ( à part l'activité) qui permet de récupérer
les informations retournées du web services.
Classe JSONParser.java
import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; public class JSONParser { String charset = "UTF-8"; HttpURLConnection conn; DataOutputStream wr; StringBuilder result; URL urlObj; JSONObject jObj = null; StringBuilder sbParams; String paramsString; public JSONObject makeHttpRequest(String url, String method, HashMap<String, String> params) { sbParams = new StringBuilder(); int i = 0; for (String key : params.keySet()) { try { if (i != 0){ sbParams.append("&"); } sbParams.append(key).append("=") .append(URLEncoder.encode(params.get(key), charset)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } i++; } if (method.equals("POST")) { // request method is POST try { urlObj = new URL(url); conn = (HttpURLConnection) urlObj.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept-Charset", charset); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.connect(); paramsString = sbParams.toString(); wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(paramsString); wr.flush(); wr.close(); } catch (IOException e) { e.printStackTrace(); } } else if(method.equals("GET")){ // request method is GET if (sbParams.length() != 0) { url += "?" + sbParams.toString(); } try { urlObj = new URL(url); conn = (HttpURLConnection) urlObj.openConnection(); conn.setDoOutput(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept-Charset", charset); conn.setConnectTimeout(15000); conn.connect(); } catch (IOException e) { e.printStackTrace(); } } try { //Receive the response from the server InputStream in = new BufferedInputStream(conn.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } Log.d("JSON Parser", "result: " + result.toString()); } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); // try parse the string to a JSON object try { jObj = new JSONObject(result.toString()); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON Object return jObj; } }
Finalement il nous reste le code d'activité :
import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; 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.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { JSONParser jsonParser=new JSONParser(); Button btpic, btnup; private Uri fileUri; String picturePath; Uri selectedImage; Bitmap photo; String ba1; public static String URL = "http://........../image.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btpic = (Button) findViewById(R.id.cpic); btpic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { clickpic(); } }); btnup = (Button) findViewById(R.id.up); btnup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { upload(); } }); } private void upload() { // Image location URL Log.e("path", "----------------" + picturePath); // Image Bitmap bm = BitmapFactory.decodeFile(picturePath); ByteArrayOutputStream bao = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte[] ba = bao.toByteArray(); ba1 = Base64.encodeToString(ba, Base64.NO_WRAP); Log.e("base64", "-----" + ba1); // Upload image to server new uploadToServer().execute(); } private void clickpic() { // Check Camera if (getApplicationContext().getPackageManager().hasSystemFeature( PackageManager.FEATURE_CAMERA)) { // Open default camera Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // start the image capture Intent startActivityForResult(intent, 100); } else { Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show(); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 100 && resultCode == RESULT_OK) { selectedImage = data.getData(); photo = (Bitmap) data.getExtras().get("data"); // Cursor to get image uri to display String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); picturePath = cursor.getString(columnIndex); cursor.close(); Bitmap photo = (Bitmap) data.getExtras().get("data"); ImageView imageView = (ImageView) findViewById(R.id.Imageprev); imageView.setImageBitmap(photo); } } class uploadToServer extends AsyncTask<Void, Void, String> { private ProgressDialog pd = new ProgressDialog(MainActivity.this); protected void onPreExecute() { super.onPreExecute(); pd.setMessage("image uploading!"); pd.show(); } @Override protected String doInBackground(Void... params) { HashMap<String, String> param = new HashMap<String, String>(); param.put("base64", ba1); param.put("ImageName", System.currentTimeMillis() + ".jpg"); JSONObject json=jsonParser.makeHttpRequest(URL,"POST",param); return "Success"; } protected void onPostExecute(String result) { super.onPostExecute(result); pd.hide(); pd.dismiss(); } } }
Commentaires
Enregistrer un commentaire
Your comment will be reviewed by moderators