How to retrieve a photo from HttpClient? - php

I am using HttpClient to make a request from my Android device to a simple HTTP server, which contains a PHP script to retrieve a picture. The picture is available inside a blob data. It means if I do this little PHP code in the server side:
file_put_contents("myPicture.png", $blob_data);
I get the picture saved in the server with a file named myPicture.png. Now I want to get this $blob_data (my picture) to save it inside my Android device, not the HTTP server. Someone can give me a hint to return the blob data from the PHP script and get the picture inside the Android device to store it locally?
Here is my HTTPClient:
#Click(R.id.btn_login)
#Background
public void LoginTrigger(){
String nUsername = username.getText().toString().trim();
String nPassword = password.getText().toString().trim();
if (nUsername.matches("") || nPassword.matches("")){
displayToast("Please insert your login!");
}
else{
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("username", nUsername));
urlParameters.add(new BasicNameValuePair("password", nPassword));
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_PROXY);
post.setHeader("User-Agent", SERVER_USER_AGENT);
try{
post.setEntity(new UrlEncodedFormEntity(urlParameters, "utf-8"));
}
catch(Exception e){
Log.getStackTraceString(e);
}
HttpResponse response = null;
try{
response = client.execute(post);
Log.e("Response Code : ", " = " + response.getStatusLine().getReasonPhrase());
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
String responseMessage = sb.toString();
checkLogin(responseMessage);
}
catch(Exception e){
Log.e("HTTP-ERROR", " = " + Log.getStackTraceString(e));
displayToast("Check your Internet connection!");
}
}
}
String responseMessage contains my blob data when I echo it in my PHP script. I just need to put this stream inside a Bitmap or something, but I've no clue about how to get it done.
Thanks if you know it!

php code (server)
<?php
header('Content-Type: image/png');
echo($blob_data);
?>
java code (device)
URL url = new URL ("http://myserver.com/myPicture.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,"myPicture.png"));
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

You need to change both the client and the server code.
The server code
Add this at the end of your PHP script
header("Content-Type: image/png");
header("Content-Length: " . mb_strlen($blob_data, '8bit'));
echo $blob_data;
exit;
The client code
Your code is not ready to read binary data, please, check out this other question on how to do it: how to download image from any web page in java

it's not recommended to send the actual file to your android app , the best way to do that is by sending a base 64 encoded a link string of the image , which will have all the meta data of the image , then load the image from base46 encoded string
$image = base64_decode($file_path);
return response::json(array('image'=>$image);
and receive it like object and render your image with the base64code image like this
i do it in js like this
var reader = new FileReader();
reader.onload = function(e) {
image_base64 = e.target.result;
preview.html("<img src='" + image_base64 + "'/>");
};
reader.readAsDataURL(file);

Related

How to display an image from mysql php into android?

I am currently trying to display an image from mysql database into my android program using an image view. However, it does not work the way I wanted to yet. The following is the php code i currently have:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
require 'connect_aircraftoperator.php';
$image = $db->query("SELECT companyImage FROM company where companyID = 2");
$getImage = $image->fetch_assoc();
$upload = $getImage['companyImage'];
header("Content-type: image/png");
echo $upload;
?>
The code displays the image just fine in the browser. The following is my current android code
void getImage() {
//String imageResult = "";
//JSONObject jArray = null;
//String Qrimage;
//Bitmap bmp;
try {
//setting up the default http client
HttpClient httpClient = new DefaultHttpClient();
//specify the url and the name of the php file that we are going to use
//as a parameter to the HttpPost method
HttpPost httpPost = new HttpPost("http://10.0.2.2//aircraftoperatorapp/leimage.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch (Exception e) {
System.out.println("Exception 1 Caught ");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//create a string builder object to hold data
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
//use the toString() method to get the data in the result
imageResult = sb.toString();
is.close();
//checks the data by printing the result in the logcat
System.out.println("---Here's my data---");
System.out.println(imageResult);
}
catch (Exception e){
System.out.println("Exception 2 Caught ");
}
try {
//creates json array
JSONArray jArray = new JSONArray(imageResult);
for (int i = 0; i < jArray.length(); i++)
{
//create a json object to extract the data
JSONObject json_data = jArray.getJSONObject(i);
imageTemp = json_data.getString("companyImage"); //gets the value from the php
}
lblTesting3.setText(imageTemp);
byte[] data = Base64.decode(imageTemp, 0);
Bitmap b = BitmapFactory.decodeByteArray(data,0,data.length,null);
imgCompany.setImageBitmap(b);
}
catch (Exception e){
//System.out.println("Exception 3 Caught ");
Log.e("lag_tag", "Error Parsing Data " + e.toString());
}
}
All I have returning is some text that probably has to do with the image I'm returning. The following text is like this in the beginning:
ÿØÿáhExifMM*vž¤¬(1´2Ò‡iè ü€' ü€..... and so on.
Is there a way I can convert this into an image that is displayable into my android program with the code I have or do I have to do something more different? I would appreciate anyone would help me! It would mean a lot! Thanks in advance!
I think the issue you're facing with is a simple decoding mistake.
HttpEntity entity = response.getEntity();
is = entity.getContent();
The InputStream you're getting from the HttpEntity contains binary image data. So you can simply copy that data into an bytearray:
...
Bitmap bitmap;
byte[] image = null;
...
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in, out, true);
image = out.toByteArray();
in.close();
bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
...
public static void copy(InputStream in, OutputStream out, boolean close)
throws IOException
{
if (in != null && out != null)
{
byte[] buffer = new byte[4096];
int count;
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count);
if (close)
{
in.close();
out.close();
}
}
}

& converted into & when $_POST request is called?

We are working on an application which has 2 modules.
Android Application.
PHP Application
PHP backend application runs on an Apache Server with Centos Server.
Android application basically clicks images, send to the server along with gps coordinates etc form information.
Now the problem arises when the image file is created on the server. When android app calls the url the '&' character is replaced by & amp;, sometimes even by & amp;& amp; and this problem repeats in some of the cases. Once this conversion thing happens, image file is not created properly.
How it can be resolved?
Same code was working alright from past year, this problem begin to arise from last month only....
Following is the code for saving the images at server end :
foreach($_POST as $key => $value) {
$_POST[$x] = $value;
}
$base=$_REQUEST['image'];
$nm=$_REQUEST['name'];
$binary=base64_decode($base);
if(file_exists("uploaded_images/".$nm.".jpg")) {
unlink("uploaded_images/".$nm.".jpg");
}
header('Content-Type: bitmap; charset=utf-8');
$str="uploaded_images/".$nm.".jpg";
$file = fopen($str, 'wb');
fwrite($file, $binary);
fclose($file);
chmod($file,0777);
$ok=1;
echo $ok;
Following is the error log which is encountered if image is not properly saved.
PHP Notice: Undefined index: name in /var/www/html/cbd/def/filesubmitnew.php
Note : filesubmitnew.php is the file name of the above code.
In Android Application for this is how the url is called:
To Create image:
if(buttontext.equals("Img1")) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
v.setImageBitmap(bitmap);
buttontext="";
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, stream);
byte [] byte_arr = stream.toByteArray();
String str1 = Base64.encodeBytes(byte_arr);
System.out.println(""+str1);
if(feuser.equals("offline_access")){
System.out.println("++==--SD CARD");
File externalStorage = Environment.getExternalStorageDirectory();
File folder = new File(externalStorage.getAbsolutePath() +mainFolder + caseId);
if (!folder.exists()) {
folder.mkdir();
}
File pictureFile = new File(externalStorage.getAbsolutePath()+mainFolder+caseId, "1.jpg");
System.out.println(pictureFile);
pictureFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(pictureFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(str1);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+pictureFile,Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent ("com.keyboardlabs.newbankge.CameraUploadService");
try {
i.putExtra("imageparams", str1);
i.putExtra("ref_id", caseId);
i.putExtra("imageId", "1");
i.putExtra("CaseType",caseType);
}
catch (Exception e) {
e.printStackTrace();
}
getApplicationContext().startService(i);
}
Following is the camerauploadservice
protected void onHandleIntent(Intent arg0) {
String imageDataBase64encoded = arg0.getStringExtra("imageparams");
String caseID = arg0.getStringExtra("ref_id");
String imageId = arg0.getStringExtra("imageId");
String caseType =arg0.getStringExtra("CaseType");
System.out.println("image_ref="+caseID+"iamgeID="+imageId+"caseType="+caseType+" URL="+URL);
callWebService(imageDataBase64encoded,caseID,imageId,caseType);
}
public void callWebService(String imageData,String refId,String imageId,String caseType){
HttpClient httpclient = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",imageData));
nameValuePairs.add(new BasicNameValuePair("ref_id",refId));
nameValuePairs.add(new BasicNameValuePair("imageId",imageId));
nameValuePairs.add(new BasicNameValuePair("CaseType",caseType));
try{
httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
System.out.println( "Response= " + the_string_response);
}catch(Exception e){
System.out.println( "0" + e.getMessage());
System.out.println("Error in http connection "+e.toString());
}
httpclient.getConnectionManager().shutdown();
}

How to Upload images to Php server and store in phpmyadmin

I am basically tring to upload image from android and upload it to php server but here i'm not getting any connection with this code or image upload .
I'm getting this error .
Error in http connection java.net.UnknownHostException: host name
but as per my knowledge i given correct connection and php file also in correct domain.
Look at my code :
UploadImage.java
public class UploadImage extends Activity {
InputStream inputStream;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://server.com/uploadimage/uploadimage.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("Error in http connection "+e.toString());
}
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
Php Code :
<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';?>
Any one known this issue ? if any one know how to store in mysql database from php file and fetch viceversa please suggest me here...
The problem is very clear ...
Error in http connection java.net.UnknownHostException: host name
means that the HttpPost cannot make a connection using the hostname you supplied - because the hostname you supplied isn't known.
If you take the hostname from this line :
HttpPost httppost = new HttpPost("http://server.com/uploadimage/uploadimage.php");
and put it in a browser on the same device what happens ... i suggest you will get an error saying unable to connect to host. If this works then i suggest you check the following line is in your manifest :
<uses-permission android:name="android.permission.INTERNET" />
Also ensure that the PHP file contains the following header if your using a JPEG:
header('Content-Type: image/jpg');
1. Need to add Internet permission in android manifest file .
<uses-permission android:name="android.permission.INTERNET" />
2. Every Time i used to see image using url but unable to see because i didnt added
echo "<img src=test.jpg>";
3.$file = fopen('test.jpg', 'wb');
4. final thing is i have to change header file as :
header('Content-Type: image/jpg; charset=utf-8');
Check Host configuration and choose right header for file upload. In your php code you have given wrong header type.
I recommend you as ManseUK said to add the permission in your Manifest.
This error is quite unclear but is often resolved by adding <uses-permission android:name="android.permission.INTERNET" />
This works for me:
// change the bitmap compress format to jpeg
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// then uploadimage.php
// note the imagecreatefromstring() function
error_reporting(E_ALL); // in case its turned off and your not seeing errors
ini_set('display_errors','1'); // confirm and browse to page
if($base) {
$ttime = intval(time());
$quality = '100';
$save_to = 'images/img-' . $ttime . '.jpeg';
$binary=base64_decode($base);
$im = imagecreatefromstring($binary);
if ($im !== false) {
header('Content-Type: image/jpg');
$idno = ImageJPEG($im, $save_to, $quality);
imagedestroy($im);
echo "iid:" . $ttime;
} else {
echo "Error:" . $ttime;
}
}

How can I make an Android app communicate with a web server over the internet?

I have an idea for an app and am currently learning Android development. I'm fairly familiar with creating simple standalone apps.
I'm also familiar with PHP and webhosting.
What I want to do is, make an android app send an image to a server via the internet and make the server return a processed image. I have no clue how I'd do that.
Can you please tell me how can I go about achieving this or which topics should I look into? Also, what scripts can I use to do the processing on the web server? Particularly, can I use PHP or Java?
Thanks!
For Image Uploading
///Method Communicate with webservice an return Yes if Image uploaded else NO
String executeMultipartPost(Bitmap bm,String image_name) {
String resp = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("domain.com/upload_image.php");
ByteArrayBody bab = new ByteArrayBody(data, image_name);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded", bab);
reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
resp=s.toString();
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
return resp;
}
//PHP Code
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "yes";
}
else {
echo "no";
}
?>
Normally we do it with http connection, you can pass the image in the
post params, for further reference please see the link
You have to create a simple php web service which accepts parameter as image bytes and which process the image and store in server. For this android app will send image data in bytes to the server using HttpPost.
For retrieving purpose you have to create a other web service which will output the file name of image from where android app can retrieve the image

Runtime exception while uploading image to the server

The below is the runtime exeception which i got while am trying to upload a image to the server.
And am trying to upload a image using my local server(WAMP) and my android code is
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/Sunset.jpg");
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.background1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.49/android/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(uploadimage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(uploadimage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("Error http connection"+e.toString());
}
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
Toast.makeText(uploadimage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting string buffer to string
Toast.makeText(uploadimage.this, "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
and this is my php code which i got from internet .
<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';
?>
Can any one help me in this to solve my problem. thanks in advance
You have to create one additional directory in c:\ then provide read, write and execute permission on it.
In your php code please write the absolute path of the storage location.
This may solve your problem.
Remember to run the IIS server in Administrator mode.
Inetpub is created by the SYSTEM user. This means that you aren't allowed to make modifications to it, or any of its subdirectories, without admin permissions. Try changing the permissions of the inetpub folder so anyone can modify the files. Right-click -> Properties -> ... I forget what to do after that. (I'm in Linux right now). If that doesn't work, make sure you are running IIS as an Administrator.

Categories