I have searched lot on Internet that how to upload image from android device to server. As a result of that, I am posting this tutorial. At server side, I used PHP script. So, you need to learn basic of PHP, because PHP is used at server side to store image. Following is a scenario that indicates how image transforms from one format to another format and finally back to original format.
Now, you understand that actually, we are sending String from android device to server not the image. Android.util package does not support the functionality of base64 encoder and decoder. So what, here is the solution.
Just go to link, http://iharder.sourceforge.net/current/java/base64/ and download the zip. Extract it and find the Base64.java file. Copy it and Past it on your project. Copy it into appropriate “src” folder.
Now, refresh Package Explorer,so that Base64.java file can be included. you will get the following error “The declared package does not match the expected package”. Fix this by opening the class file and adding a package declaration that matches your project. Following is the screenshot.
Now, following is the java code that converts the image into String and sends it to Server. You can get the pdf from here.
public class upload extends Activity {
InputStream is;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.a1);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://10.0.2.2:80/android/base.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
}
Server Side:
Now install the server. Create the file base.php. Create another file empty file test.jpg. Make sure that path of this two file will be same. At server side base.php will be executed. This PHP Script will open test.jpg file and write the binary data.
So, now you understand that test.jpg is the result of this example. Here is the PHP code, you can get the pdf from here.
<?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>';
?>
Do not forget to insert following permission in AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Following are the links of other Post on Android.
Android : ContextMenu & SubMenu
Android : Connecting to MySQL using PHP
Android : Sliding Drawer
Android Countdown Timer
Getting started with Android Map View: Displaying a location by Marker
Simple Progress Bar in Android using Thread
Android listview with image and text
Manage & Developed by Sptechnolab.com



70 comments
dia
March 30, 2011 at 10:16 pm (UTC 5.5) Link to this comment
Hi there! I followed the code step by step but the test.jpg is always 0KB.
please help!
[Translate]
bhargav
March 31, 2011 at 5:13 am (UTC 5.5) Link to this comment
If you are working on Linux, then change the Owner to nobody and Group to nogroup of test.jpg image. Make sure that you use proper url of php file in android. Php file and tets.jpg should be in same folder. If you still having a problem, then send me extra information.
[Translate]
dia
April 6, 2011 at 7:48 pm (UTC 5.5) Link to this comment
Thanks for replying!
I’m working on windows.
i kept trying to change the folder not to be read only, but it still shows read only
I added on the php side a couple of lines to write to a log file located in same place with the image, and that one saves ok, so it’s not a write access on the folder.
please let me know what else can I try.
thanks!!!
[Translate]
REAL HP SERVERS
March 31, 2011 at 8:56 pm (UTC 5.5) Link to this comment
wow….That’s really great brief.That’s very helpul.Thanks a lot.
[Translate]
vn
April 3, 2011 at 8:16 pm (UTC 5.5) Link to this comment
Hi
I changed the Owner to nobody and Group to nogroup of test.jpg image but the test.jpg is always 0KB.
please help
[Translate]
bhargav
April 4, 2011 at 5:23 am (UTC 5.5) Link to this comment
Reply me some information like LogCat error message.
[Translate]
Pao|
April 5, 2011 at 1:23 pm (UTC 5.5) Link to this comment
I get the same problem, i’m working on windows, using xampp.
i’m using a real device (no emulator).
These are the steps:
1. Run application on my device.
2. Open a navigator (chrome) and go to http://192.168.0.118/test/uploads/img/base.php
2.1. I see on the page:
3. Then i go to C:\xampp\htdocs\test\uploads\img , and the file test.jpg is 0kb.
Could you share a zip file with your code?
[Translate]
bhargav
April 6, 2011 at 5:56 am (UTC 5.5) Link to this comment
Make sure that you have given internet permission in AndroidManifest.xml file.
It is not require to open a navigator, but you have to change the url of base.php file in the java code of this example. You should write original url of php file.
In windows, it is not require to create empty test.jpg file, because php script will automatically create it.
[Translate]
Pao
April 5, 2011 at 1:28 pm (UTC 5.5) Link to this comment
On the previous post:
in the step 2.1 this is what i see:
<img src="test.jpg"/>
I have forgotten says that im using android 2.2
Regards!
[Translate]
bhargav
April 6, 2011 at 5:59 am (UTC 5.5) Link to this comment
This example successfully woks on Android 2.2.
[Translate]
Marco Montes
April 6, 2011 at 4:08 am (UTC 5.5) Link to this comment
hi, thanks a lot, its working fine, but i tried to save the binary files as blobsin a mysql db and trying to retrieve them later. it seems they are already in the db but cant find a way to show them as .jpgs… of course i have an auto imcrement Id colum to make the query. the idea is give each image a unique url , istead of replacing test.jpg file, is there a easier way???
[Translate]
bhargav
April 6, 2011 at 6:15 am (UTC 5.5) Link to this comment
It is not good idea to store image in mysql as blobs. This example stores image at server side in jpg format. Now, the idea is that you can store the path of image in mysql. In windws, php script automatically creates jpg files, you do not have the worry about creating empty files. Just you have to give filename for each image in php script. Now you can query the database and have the unique path of each jpg file.
[Translate]
Marco Montes
April 6, 2011 at 2:05 pm (UTC 5.5) Link to this comment
yeap not a good idea handling BLOBS , first i was trying something like this to store images in files named as id’s but never worked
$buffer=base64_decode($base);
$filename = “images/”.$row['ID'].”.jpg”;
$mystring = fopen($filename, ‘wb’);
$handle = fopen($filename, ‘wb’);
$numbytes = fwrite($handle, $buffer);
fclose($handle);
echo $filename;
print ”;
[Translate]
bhargav
April 8, 2011 at 5:02 am (UTC 5.5) Link to this comment
Following is the php code that retrieves image data and filename of image from android. Stores this image in ‘img’ folder. After that enters image path in database.
<?php
$base=$_REQUEST['image'];
$filename=$_REQUEST['filename'];
$buffer=base64_decode($base);
$path = "img/".$filename.".jpg";
$handle = fopen($path, 'wb');
$numbytes = fwrite($handle, $buffer);
fclose($handle);
$conn=mysql_connect(“localhost”,”",”");
mysql_select_db(“test”);
$sql=”insert into IMAGE (path) values(‘ “.$path.” ‘)”;
$r=mysql_query($sql);
?>
[Translate]
Marco Montes
April 8, 2011 at 5:11 am (UTC 5.5) Link to this comment
woww, merci beaucoup, this blog rules!!!
[Translate]
Handy
September 15, 2011 at 9:30 am (UTC 5.5) Link to this comment
hi there, my project is similiar to this, i want to save a image path to my database, it work but the file doesn’t have a name, am i missing something? does the name’s file came from the same name from image file in my sdcard? thanks
[Translate]
dia
April 6, 2011 at 8:17 pm (UTC 5.5) Link to this comment
Hi there. You mentioned it’s working ok for you. Are you using php on windows? Are you using Apache or IIS? I’m trying to see if it’s an issue on php side or on android.
Did it always work for you, or you also had to do some changes?
thanks
[Translate]
bhargav
April 8, 2011 at 5:54 am (UTC 5.5) Link to this comment
I have tested this application in xampp and wamp server and it works fine.
[Translate]
dage_java
April 7, 2011 at 2:49 pm (UTC 5.5) Link to this comment
I can’t get it
can you give me a zip file …
where is the layout.xml
I am is an new~!
wordhao@gmail.com
[Translate]
Marco Montes
April 8, 2011 at 5:05 am (UTC 5.5) Link to this comment
the process works great but it takes a while, how can we set a process dialog, or should we do this within a service?
[Translate]
bhargav
April 8, 2011 at 5:31 am (UTC 5.5) Link to this comment
You can set progress dialog using following code in java,
ProgressDialog MyDialog = ProgressDialog.show( MyActivity.this, ” ” , ” Loading. Please wait … “, true);
to show dialog: MyDialog.show();
to dismiss it: MyDialog.dismiss();
[Translate]
RaymondHo
April 12, 2011 at 12:36 pm (UTC 5.5) Link to this comment
hey man,
your tutorial is really helpful!!!
help my FYP a lot!
Thank you very much!
[Translate]
Pradeep
April 12, 2011 at 2:07 pm (UTC 5.5) Link to this comment
Hi Bhargav,
The code worked absolutely fine for me thank u……wat i would like to know is that can the server side script be written in jsp for this example …..if u know can u please suggest me the code…..it would be of great help…thank u in advance
[Translate]
Akshay Nayak
April 23, 2011 at 7:45 am (UTC 5.5) Link to this comment
thanks a lot bhargav, its working fine after fixing a lot of errors….
[Translate]
Akshay Nayak
April 26, 2011 at 4:15 am (UTC 5.5) Link to this comment
Can u please tell me how can i access the image stored in sd card rather than an image in drawable hdpi folder?
i have tried a code but its giving force close… can u please help me out…..
package pic.upload;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
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 android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class picture extends Activity {
InputStream is;
String imageFilePath;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmapOrg= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() +”/mypic.jpg”);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList nameValuePairs = new
ArrayList();
nameValuePairs.add(new BasicNameValuePair(“image”,ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost(“http://172.16.6.41/mobile_insurance/base.php”);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e(“log_tag”, “Error in http connection “+e.toString());
}
}
}
[Translate]
bhargav
April 28, 2011 at 5:58 am (UTC 5.5) Link to this comment
Code works fine and successfully uploads image at server side. An error occurred, because you are not using sd card in emulator. So, create sd card and import images into sd card.
[Translate]
Russ
May 6, 2011 at 8:50 pm (UTC 5.5) Link to this comment
I had everything working fine as one of my very initial Android aps. When I went to re-build it the right way, I started getting errors. Now, when I try to call the Upload class, I get an error like it can’t find the class- but the error is in runtime. “Source not found.” It gives a button “Edit Source Lookup Path…” What in the world do I do?
Great resource, though, this code. Very cool. The PHP I am using is (and works outside the Android app!):
[Translate]
Marco Montes Neri
May 13, 2011 at 2:05 pm (UTC 5.5) Link to this comment
hi, i got this code working fine but can’t find a way to have a toast saying “sending” cause, it seems it’s not responding, could you plese tell me where i should put the whie {… Toast.makeText… stuff, thanks again !!
[Translate]
bhargav
May 14, 2011 at 5:44 am (UTC 5.5) Link to this comment
Hi, here is a link of pdf file, upload image with progress dialog
[Translate]
Pradeep
May 15, 2011 at 6:55 am (UTC 5.5) Link to this comment
Hi,
I hve tired your code….from the code it is clear that it handles response…what should be done to display the response on the client…should any changes be made in the php script..Thank u waiting for reply
[Translate]
bhargav
May 17, 2011 at 5:00 am (UTC 5.5) Link to this comment
Yes, you can refer my another blog Connecting android to mysql. With the help of example in blog, you can add image path to mysql.
[Translate]
anonimouuuus
May 20, 2011 at 5:50 pm (UTC 5.5) Link to this comment
This fits perfectly with my plans to take over the world!! moahaha
Really nice blog you have here, all code works 100% and feedback is awesome!
Keep posting!!!!!!!
thanks bhargav
[Translate]
subakar
May 21, 2011 at 5:12 am (UTC 5.5) Link to this comment
i got error in line String ba1=Base64.encodeBytes(ba); saying that “The method encodeBytes(byte[]) is undefined for the type Base64″ .Anyone know the soln???????? i’m using php server as back end………
[Translate]
bhargav
May 24, 2011 at 5:08 am (UTC 5.5) Link to this comment
Have you past Base64.java file into your project?
[Translate]
yuki
June 8, 2011 at 3:23 am (UTC 5.5) Link to this comment
Hi, I’m having the same error as subakar but I have pasted Base64.java into the src, anyone has any idea?
[Translate]
james
October 10, 2011 at 10:03 pm (UTC 5.5) Link to this comment
Same problem, base64.java is in the src, method is in there, no idea why it won’t work its a public method
[Translate]
andro
January 21, 2012 at 4:31 am (UTC 5.5) Link to this comment
Hi, I have the same problem with subakar, those anyone have fixed it?
I really need the solution of it. Thanks
[Translate]
Seemas
March 19, 2012 at 5:35 am (UTC 5.5) Link to this comment
first remove the import of Base64
and then again import it then this error will be fixed
this happends because we have already imported Base64 of java libary
[Translate]
Jen
February 10, 2012 at 6:24 pm (UTC 5.5) Link to this comment
i had this problem too. i used this instead and it worked
String ba1 = Base64.encodeToString(ba, 0);
the two parameters are the byte[] and a flag. i didn’t know which default to use so i set it to 0. that might be wrong, but it works in the end
[Translate]
arg_vedder
May 24, 2011 at 8:30 pm (UTC 5.5) Link to this comment
Hey, this code works great! Everything goes fine when sending 50kb img, but im having some problems sending larger images (300kb or so). Besides im getting no errors, just the file does not get uploaded.
Is there any limit sending text via httppost? maybe a connection timeout?
thanks!
[Translate]
subakar
June 8, 2011 at 5:27 am (UTC 5.5) Link to this comment
hi Yuki…check the android version u using…in android 1.6 its working fine……its not working in android 2.2, i did’t check in 2.1……..now, for me its working well….
[Translate]
June
June 18, 2011 at 12:06 am (UTC 5.5) Link to this comment
1) Do you guys know how to create an original url??
2) where should I put this base.php?? in my src??? Please, let me know thanks.
[Translate]
Nisha
June 18, 2011 at 8:27 pm (UTC 5.5) Link to this comment
Hii there,
I am making an app, which should be able to send image to php server, where image is obtained, either by accessing camera by the app or access the image of gallery. Till now, I am able to access the camera, capture image,store it to gallery and send it to server nd store it there successfully. Its also able to access the gallery, select the image, however, its nt able to send it to the server; gives the “Out of memory ” error. I am really confused because, the same image, which is captured before n send to server successfully, cannot be send when selected from the gallery. Code is given below. Can anyone please, point out the error please…..
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case ACTIVITY_SELECT_IMAGE:
if(resultCode == RESULT_OK){
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 filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1 = Base64.encodeBytes(ba);
nameValuePairs.add(new BasicNameValuePair(“image”, ba1));
……..
……..
}
break;
It gives out of memory error in line:
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
Thanx a lot.
[Translate]
webdevbyjoss
September 11, 2011 at 12:03 pm (UTC 5.5) Link to this comment
Hi, I have exactly the same problem as described in your post.
My application crashes with out of memory error on
boolean result = bmp.compress(Bitmap.CompressFormat.JPEG, 99, fOut);
Have you resolved this error?
[Translate]
Fep
August 3, 2011 at 10:21 am (UTC 5.5) Link to this comment
Hi very good example thanks.
I’d like to do the same but upload a video instead of an image. What would be different ?
[Translate]
Niti (thailand)
August 7, 2011 at 9:28 am (UTC 5.5) Link to this comment
very useful code. thanks to u, y bhargav.
Initially, I had problem of file was not created.
The root cause is because of Windows7′s permission. I need to allow user of the www’s director to full control
I use IIS w fastPHP
[Translate]
med
August 29, 2011 at 6:00 pm (UTC 5.5) Link to this comment
fantastic Tutorial! It works fine and at the first try! I’m currently working on our Android APP so once again! THX
[Translate]
thilina sampath
September 12, 2011 at 7:25 am (UTC 5.5) Link to this comment
[Translate]
dhaval
September 14, 2011 at 1:41 pm (UTC 5.5) Link to this comment
i got error like :
Error in http connection…. i try this on local server
http://localhost/dhaval/and/base.php
[Translate]
Handy
September 15, 2011 at 6:43 am (UTC 5.5) Link to this comment
thank you for ur tutorial, i’ve uploaded the image
do you know how to retrieve it back to android? can u show me the example? thanks before
[Translate]
chenhou90
October 6, 2011 at 1:57 am (UTC 5.5) Link to this comment
can i send other information of the image to php, like for example date the picture is taken?
[Translate]
bhargav
October 7, 2011 at 4:54 am (UTC 5.5) Link to this comment
Yes, you can send other information. Here is a link of nice blog. It will help you to send data with image as well.
[Translate]
ajimukhlis
October 19, 2011 at 1:27 pm (UTC 5.5) Link to this comment
Ow thanks man, it really works
[Translate]
Raja
October 28, 2011 at 2:55 pm (UTC 5.5) Link to this comment
hello all….can1 anyone tell me whr was d image reciding which is being sent…wat is the name of the image in the above code….m a newbie..a bit confused…plz help…
[Translate]
Leffy
November 10, 2011 at 8:55 am (UTC 5.5) Link to this comment
I am having the same issue as described earlier by arg_vedder.
This code works fine if I try to upload smaller files, however once I go above ~100kb this no longer works and I am not sure why.
Also compression is not an option for me as it would reduce the image quality too much so I am looking for an alternative solution.
[Translate]
Eric
November 20, 2011 at 3:27 am (UTC 5.5) Link to this comment
I am having the same issue as described earlier by arg_vedder.
I’m not sure if it’s because the decode file have a size limitation…I guess I need to check for file size first before decoding it?
[Translate]
wangpeng
November 21, 2011 at 7:28 am (UTC 5.5) Link to this comment
i copy you code,sometimes is good,sometimes i am use other phone is not good,in moto 2.1 always good,samsung not always run well
[Translate]
sanjay
January 25, 2012 at 8:03 am (UTC 5.5) Link to this comment
Hi
i m new to android development
can you provide me full source for capture and upload project
Thanks
[Translate]
Matej
February 6, 2012 at 9:03 pm (UTC 5.5) Link to this comment
Hi! There are two libraries for InputStream:
a) java.io.InputStream;
b) [your.package.name].Base64.InputStream;
Which one should I use for InputStream is; ?
[Translate]
Jahanzaib
February 26, 2012 at 7:01 am (UTC 5.5) Link to this comment
Hi this Tutorial is great.
I can successfully send data to the server can you tell me after receiving the same data i am unable to convert that same data into bitmap.
Can you please tell me how to convert String(string from server) of an image into bitmap , So i can easily set this bitmap into Image View.
[Translate]
Kevin
March 4, 2012 at 10:41 pm (UTC 5.5) Link to this comment
Thanks! works great! I had to change the line of code so it reads
String ba1 = Base64.encodeToString(ba, 0);
but everything else was flawless. Nice work.
[Translate]
Madhavan
March 7, 2012 at 9:48 am (UTC 5.5) Link to this comment
Very very thanks to u……… it works well and images stored in the server… path is stored in the mysql db..
[Translate]
Mahmoud
March 12, 2012 at 9:56 pm (UTC 5.5) Link to this comment
the code is worked for me but can i return image url instead of image bitmap?
[Translate]
Muhammad Sohail
March 15, 2012 at 7:25 am (UTC 5.5) Link to this comment
i have copied and pasted your code and made many corrections but still there is one error plz help
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.a1);
error is: a1 cannot be resolved or is not a field
[Translate]
Farooq Arshed
April 7, 2012 at 9:54 am (UTC 5.5) Link to this comment
I have got the same problem. Please respond.
[Translate]
cvd
March 28, 2012 at 9:24 pm (UTC 5.5) Link to this comment
how can I upload an image from an imageview from the layout xml? similarly like findviewbyid.imgid
My layout name is main.xml and image id is imgid
kindly help me…
[Translate]
chand
April 6, 2012 at 12:08 pm (UTC 5.5) Link to this comment
How can I upload the image from the gallery?
[Translate]
ganesh
April 7, 2012 at 4:17 pm (UTC 5.5) Link to this comment
hi ! can anyone suggest me java alternative for above used php script on server side.
Any help will be appreciated..
[Translate]
Amit Suri
April 28, 2012 at 12:31 pm (UTC 5.5) Link to this comment
Hi Everyone
I am new in Android and i have a task:-
1. Allow users to Capture an image.
2. Send that image to Web Server or Remote Server.
My Server path is(IP address>C:>Folder(Inside this folder save captured images))
Please anyone help me and give me complete source code or tell URL from where i can get needful Source,
It’s very urgent.
My email id is:andoid.amitsuri@gmail.com
Thnx in advance
Thanks
Amit Suri
[Translate]
tasnim ahmed
May 26, 2012 at 6:07 pm (UTC 5.5) Link to this comment
Successfully posted image to the server.but took so much time
[Translate]