Javascript required
Skip to content Skip to sidebar Skip to footer

How to Upload Image in Android Studio

Hi all,

In today's tutorial I will prove you lot how to send an image to server using POST method in ANDROID.

Uploading an prototype to server is a basic requirement in many of our awarding.
Sending information to server which is using a PHP Script is already explained in this example .
At present in this example I will show you how to send an image file.

For that first nosotros have to read the file, put information technology in nameValuePairs and and then send using HttpPost.

I accept already shown you iii other methods on uploading a file to server. If y'all want y'all tin can cheque these posts.

  • How to Upload Multiple files in i asking forth with other string parameters in android?
  • Uploading audio, video or image files from Android to server.
  • How to upload an paradigm from Android device to server? – Method four

These are for downloading files from the server.

  • How to Download an prototype in ANDROID programatically?
  • How to download a file to your android device from a remote server with a custom progressbar showing progress?

if you want to use the android using php and mysql
please check these posts.

  • Android phpMysql connexion
  • Android phpmySQL connectedness redone.

Make easy money with infolinks

Add Permission

Add "android.permission.INTERNET" permission to your AndroidManifest.xml file.

Note

You lot need to add the below to your build.gradle since Apache library is deprecated by Google.

android {
useLibrary 'org.apache.http.legacy'
}

build.gradle

Our Sample build.gradle may look like this.

use plugin: 'com.android.application'  android {     compileSdkVersion 23     buildToolsVersion "23.0.3"      defaultConfig {         applicationId "com.coderzheaven.uploadimage"         minSdkVersion 21         targetSdkVersion 23         versionCode ane         versionName "one.0"     }     buildTypes {         release {             minifyEnabled faux             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'         }     } }  android {     useLibrary 'org.apache.http.legacy' }  dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])     testCompile 'junit:junit:iv.12'     compile 'com.android.support:appcompat-v7:23.ii.1'     compile 'com.android.support:design:23.2.1' }        

Layout

Our Sample XML layout will look similar this.

<?xml version="i.0" encoding="utf-eight"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     app:layout_behavior="@string/appbar_scrolling_view_behavior"     tools:context="com.coderzheaven.uploadimage.MainActivity"     tools:showIn="@layout/activity_main">      <Push         android:id="@+id/btnSelect"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Select Image" />      <ImageView         android:id="@+id/imgView"         android:layout_width="300dp"         android:layout_height="300dp"         android:layout_gravity="eye" />      <Push         android:id="@+id/btnUpload"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Upload Image" />      <TextView         android:id="@+id/txtStatus"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginTop="20dp"         android:gravity="center"         android:text=""         android:textColor="@android:color/holo_green_light" />  </LinearLayout>        

Make easy money with infolinks

Android Source Code

We volition accept a carve up grade for sending image.

Create a class named "UploadImageApacheHttp" and re-create the below contents to it.
Earlier that, download the Base64 file from here which encodeBytes in Base64 Format.
Add information technology to your projection.

File Upload Utility class

package com.coderzheaven.uploadimage;  import android.graphics.Bitmap; import android.bone.Handler; import android.util.Log;  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 java.io.ByteArrayOutputStream; import coffee.util.ArrayList;  public class UploadImageApacheHttp {      public static final String TAG = "Upload Image Apache";      public void doFileUpload(final String url, final Bitmap bmp, final Handler handler){          Thread t = new Thread(new Runnable() {             @Override             public void run() {                  Log.i(TAG, "Starting Upload...");                 final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();                 nameValuePairs.add(new BasicNameValuePair("image", convertBitmapToString(bmp)));                  endeavour {                     HttpClient httpclient = new DefaultHttpClient();                     HttpPost httppost = new HttpPost(url);                     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));                     HttpResponse response = httpclient.execute(httppost);                     Cord responseStr = EntityUtils.toString(response.getEntity());                     Log.i(TAG, "doFileUpload Response : " + responseStr);                     handler.sendEmptyMessage(1);                 } take hold of (Exception e) {                     System.out.println("Error in http connection " + eastward.toString());                     handler.sendEmptyMessage(0);                 }             }         });         t.showtime();      }      public String convertBitmapToString(Bitmap bmp){         ByteArrayOutputStream stream = new ByteArrayOutputStream();         bmp.shrink(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format y'all want.         byte[] byte_arr = stream.toByteArray();         String imageStr = Base64.encodeBytes(byte_arr);         return imageStr;     } }        

Make easy money with infolinks

Now the Action that implements it.

Notation : Brand sure you select the prototype from the Gallery, because this demo is designed for selecting from Gallery.

MainActivity

package com.coderzheaven.uploadimage;  import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.cyberspace.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.back up.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView;  import java.io.IOException;  public class MainActivity extends AppCompatActivity implements View.OnClickListener {      public static final String TAG = "Upload Prototype";      // I am using my local server for uploading image, yous should replace it with your server address     public static final String UPLOAD_URL = "https://coderzheaven.com/sample_file_upload/upload_image.php";      public static final Cord UPLOAD_KEY = "upload_image";      individual int PICK_IMAGE_REQUEST = 100;      private Button btnSelect, btnUpload;     private TextView txtStatus;      individual ImageView imgView;      private Bitmap bitmap;      private Uri filePath;      private String selectedFilePath;      @Override     protected void onCreate(Packet savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);         setSupportActionBar(toolbar);          imgView = (ImageView) findViewById(R.id.imgView);         btnSelect = (Button) findViewById(R.id.btnSelect);         btnUpload = (Button) findViewById(R.id.btnUpload);         txtStatus = (TextView) findViewById(R.id.txtStatus);          btnSelect.setOnClickListener(this);         btnUpload.setOnClickListener(this);      }      Handler handler = handler = new Handler() {         @Override         public void handleMessage(Bulletin msg) {             Log.i(TAG, "Handler " + msg.what);             if (msg.what == 1) {                 txtStatus.setText("Upload Success");             } else {                 txtStatus.setText("Upload Error");             }         }      };      private void showFileChooser() {         Intent intent = new Intent();         intent.setType("epitome/*");         intent.setAction(Intent.ACTION_GET_CONTENT);         startActivityForResult(Intent.createChooser(intent, "Select Paradigm"), 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() != zippo) {              filePath = data.getData();             selectedFilePath = getPath(filePath);             Log.i(TAG, " File path : " + selectedFilePath);             try {                 bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);                 imgView.setImageBitmap(bitmap);             } take hold of (IOException eastward) {                 eastward.printStackTrace();             }         }     }      public Cord getPath(Uri uri) {         String[] project = {MediaStore.Images.Media.DATA};         Cursor cursor = managedQuery(uri, projection, nothing, null, nix);         int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.Information);         cursor.moveToFirst();         render cursor.getString(column_index);     }      private void uploadImage() {          UploadImageApacheHttp uploadTask = new UploadImageApacheHttp();         uploadTask.doFileUpload(UPLOAD_URL, bitmap, handler);      }      @Override     public void onClick(View five) {         if (v == btnSelect)             showFileChooser();         else {             txtStatus.setText("Uploading Started...");             uploadImage();         }     } }        

Note : You should do networks operations inside a thread but.
AND you lot cannot change UI elements inside a UIThread only.

< Upload Image

Add Base64.java to your project

However you can put in your own package but don't forget to change the packet proper name otherwise you will become mistake.

Server office

Create a folder named Upload_image_ANDROID in your htdocs folder and inside that create a file named upload_image.php and copy this code into it.

I am saying the htdocs binder because I am using XAMPP. You change this according to your use.

< ?php 	$base=$_REQUEST['image']; 	 $binary=base64_decode($base); 	header('Content-Type: bitmap; charset=utf-viii'); 	$file = fopen('uploaded_image.jpg', 'wb'); 	fwrite($file, $binary); 	fclose($file); 	echo 'Image upload consummate!!, Please check your php file directory……'; ?>        

Now run your plan and check the folder in which your php file resides.
Note: Make sure your server is running.
Here I am uploading the icon image itself.

If yous want to upload some other file in your SDCARD you lot have to modify this line to give the exact path

          Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);        

For instance if I take to upload a file residing in my SDCARD I would change the path like this.

          Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/android.jpg");        

Source Code

You tin download the complete Android studio Source Code from hither.

Please send your comments to coderzheaven@gmail.com

seccombemattlas.blogspot.com

Source: https://www.coderzheaven.com/2011/04/25/android-upload-an-image-to-a-server/