Tuesday 21 January 2014

Android Upload Image to Php Server

Today I will write a code for upload image to php server in android in string .You need to decode string file in php server using Base64 .

Step 1: Create Project  UploadImageToServer .

Step 2 : Write Code in MainActivity 

package com.ritesh.uploadimage;

import java.io.ByteArrayOutputStream;

import org.json.JSONObject;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
public static final int RESULT_LOAD_IMAGE = 10;
private static final int CAMERA_REQUEST = 1888;
String imagestring="";
Bitmap photo;
ImageView setimage;
Utils utils;
String message;
ProgressDialog pDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button ButtonCamera=(Button)findViewById(R.id.buttonCamera);
Button buttonGallery=(Button)findViewById(R.id.buttongallery);

Button ButtonUpload=(Button)findViewById(R.id.buttonupload);
setimage=(ImageView)findViewById(R.id.image);
ButtonCamera.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//Capture image from camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(intent, CAMERA_REQUEST);
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//Capture image from gallery
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
ButtonUpload.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
utils=new Utils();
new UploadImage().execute();
}
});
}





@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {

Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();


   photo=Utils.decodeSampledBitmapFromPath(picturePath, 400, 400);

loadImage();

 } else  if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)  {

 photo = (Bitmap) data.getExtras().get("data");


loadImage();




}}


       private void loadImage() {
     // TODO Auto-generated method stub
 
      Log.e("addimg", "imgggg");
      //resize image according to your need and replace value of 200 and 200
      Bitmap btm00 = Utils.getResizedBitmap(photo, 200, 200);
      setimage.setImageBitmap(btm00);
       
          ByteArrayOutputStream bao = new ByteArrayOutputStream();
       
          photo.compress(Bitmap.CompressFormat.JPEG, 90, bao);
          byte[] ba = bao.toByteArray();
          imagestring = Base64.encodeBytes(ba);
 }
       class UploadImage extends AsyncTask<String, String, String>{
       
      @Override
   protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    ProgressDialog pDialog=new ProgressDialog(MainActivity.this);
    pDialog.setMessage("Sending..");
    pDialog.setCancelable(true);
    pDialog.show();
   
   
   }

      @Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
JSONObject json=utils.SendToServer(imagestring);
message=json.getString("MSG");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}


return null;
   }
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub

pDialog.dismiss();
Toast.makeText(MainActivity.this, "Hello :"+message, Toast.LENGTH_LONG).show();
}
               }
       
}



Step 3: Write this code in JSONParser

package com.ritesh.uploadimage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
private InputStream is = null;
    private JSONObject jObj = null;
    private String json = "";
 
    // constructor
    public JSONParser() {
 
    }
    
    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, "utf-8"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
    }
    is.close();
    json = sb.toString();
    Log.e("JSON", json);
    } catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
    jObj = new JSONObject(json);
    } catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

    }
    
    public JSONObject getJSONFromUrl(String url) throws IllegalStateException, IOException, JSONException {
 
// Making HTTP request
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(is,
"utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();

// try parse the string to a JSON object
jObj = new JSONObject(json);

// return JSON String
return jObj;
 
    }
}


Step 4: Write this Code in Utils

package com.ritesh.uploadimage;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

public class Utils {
public static Bitmap decodeSampledBitmapFromPath(String pathName, int reqWidth, int reqHeight) {
   // First decode with inJustDecodeBounds=true to check dimensions
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeFile(pathName, options);

   // Calculate inSampleSize
   options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

   // Decode bitmap with inSampleSize set
   options.inJustDecodeBounds = false;
   return BitmapFactory.decodeFile(pathName, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
   // Raw height and width of image
   final int height = options.outHeight;
   final int width = options.outWidth;
   int inSampleSize = 1;
   if (height > reqHeight || width > reqWidth) {
       if (width > height) {
           inSampleSize = Math.round((float)height / (float)reqHeight);
       } else {
           inSampleSize = Math.round((float)width / (float)reqWidth);
       }
   }
   return inSampleSize;
}
public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}
public JSONObject SendToServer(String imagestring) {
JSONParser jsonParser=new JSONParser();
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Change your params (image)
 params.add(new BasicNameValuePair("image", imagestring));
//Change your server link and replace to this one (www.exampleupladurl.com)
 JSONObject json = jsonParser.getJSONFromUrl("www.exampleupladurl.com", params);
 return json;
}
}

Step 5: Write this Code in Manifest file 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ritesh.uploadimage"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ritesh.uploadimage.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Step 5: Downlaod Base64.java and insert in to your project  .

Run the Project







No comments:

Post a Comment