0

How posting of Image works in android

  • I am a newbie & i am looking for a step-by step instructions on how posting of images take place in android
  • Are there any good sources of information in the internet to learn this
  • All i am trying to learn is get an image from imageview and post it to server

What i have tried ?

i have learnt posting strings to server


Here is how i post srtings to server

activity_main.xml

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="32dp"
        android:clickable="false"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/imageView1"
        android:text="Click to upload Image"
        android:textSize="15dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/NAME_EDIT_TEXT_ID"
        android:layout_alignParentLeft="true"
        android:clickable="false"
        android:text="NAME"
        android:textSize="20dp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/NAME_EDIT_TEXT_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/CITY_EDIT_TEXT_ID"
        android:layout_alignRight="@+id/button1"
        android:layout_marginBottom="30dp"
        android:ems="10" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/CITY_EDIT_TEXT_ID"
        android:layout_alignLeft="@+id/textView2"
        android:clickable="false"
        android:text="CITY"
        android:textSize="20dp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/CITY_EDIT_TEXT_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/NAME_EDIT_TEXT_ID"
        android:layout_centerVertical="true"
        android:ems="10" />

    <Button
        android:id="@+id/SUBMIT_BUTTON_ID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="47dp"
        android:text="SUBMIT" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

    Button submit;
    EditText name, City;
    ProgressDialog pDialog;

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

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
        name = (EditText) findViewById(R.id.NAME_EDIT_TEXT_ID);
        City = (EditText) findViewById(R.id.CITY_EDIT_TEXT_ID);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();


            }
        });
    }


    public void postData() {
        // Create a new HttpClient and Post Header

        // You can use NameValuePair for add data to post server and yes you can
        // also append your desire data which you want to post server.

        // Like:
        // yourserver_url+"name="+name.getText().toString()+"city="+City.getText().toString()

        String newurl = "?" + "Key=" + name.getText().toString();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://My-URL"+newurl);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("Name", name.getText()
                    .toString()));
            nameValuePairs.add(new BasicNameValuePair("city", City.getText()
                    .toString()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            Log.v("Response", response.toString());

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }

    public class MainTest extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            postData();

            return null;
        }

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

            super.onPostExecute(result);
            // data=jobj.toString();
            pDialog.dismiss();

        }

    }

}

Now how can i modify the code so that i get the image from imageview and send it to the server ?

  • Any guidance would be helpful
  • I am a newbie ,so please go easy on with answers

Thanks

1

2 Answers 2

4

Following is a scenario that indicates how image transforms from one format to another format and finally back to original format.

enter image description here

try following code

Android side

private void uploadToServer(byte[] data) {
    Bitmap bitmapOrg = BitmapFactory.decodeByteArray(data, 0, data.length);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte[] ba = bao.toByteArray();
    String ba1 = Base64.encodeBytes(ba);
    final ArrayList<NameValuePair> nameValuePairs = new
    ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("image", ba1));
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new
                HttpPost("http://www.yoururl.com");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                // HttpEntity entity = response.getEntity();

                // is = entity.getContent();
                // String the_string_response =
                // convertResponseToString(response);
                // Log.e("log_tag", "Image Uploaded  "+the_string_response);
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
            }
        }
    };

}

Server side

<?php

$base=$_REQUEST['image'];

echo $base;

// base64 encoded utf-8 string

$binary=base64_decode($base);

// binary, utf-8 bytes

header('Content-Type: bitmap; charset=utf-8');

// print($binary);

//$theFile = base64_decode($image_data);

$file = fopen('test.jpg', 'wb');

fwrite($file, $binary);

fclose($file);

echo '<img src=test.jpg>';

?>

Complete Tutorial

Sign up to request clarification or add additional context in comments.

2 Comments

[+1] for the tutorial Link .... I also read the answer of Suhail Mehta .... is that a different way of getting work done .... or both ur solution and his are the same ? .... Why is he using MultipartEntity library ?
@ Ketan ......... Hey i understood your concept completely .... but ...When i need to use Suhail Mehta answer solution.... insted of your solution ....... or your solution is sufficient in all the scenarios ?
1
You have use multi part to post images to the server from android
public static JSONObject  multiPart(final String url,Bitmap bm) throws Exception 
    {
        HttpResponse response = null ;
        InputStream is = null;
        BufferedReader in = null;
        JSONObject jObject = null;
        HttpPost httppost = new HttpPost(url);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        HttpClient httpClient = getHttpClient();
        if(bm!=null){
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.PNG, 75, bos);
            byte[] data = bos.toByteArray();
            ByteArrayBody bab = new ByteArrayBody(data, name+".png");
            entity.addPart("file", bab);
        }

        httppost.setEntity(entity);
        try {
            response =  httpClient.execute(httppost);
             HttpEntity resEntity = response.getEntity();

            is = resEntity.getContent();
            in = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),
                    1024 * 4);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String result = "";
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            result = sb.toString();

            jObject = new JSONObject(result);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
         //   e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
         //   e.printStackTrace();
        }

     finally {
        in.close();

    }
    // jObject.getString(name);
     return jObject;
    }

First convert your image to bit map and then pass the bitmap to this method.And dont forget to add the following jar to libs:- httpmime-4.2-beta1.jar,apache-mime4j-0.6.1.jar

2 Comments

[+1] for information ...... but how is Ketan answer ? .... he has not used multipartentity ? .... is that more feasable solution ? .... how is that solution different from your's ?
for big chunk of data we use multipart

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.