3

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!

Nizar B.
  • 3,098
  • 9
  • 38
  • 56
  • Can you share the HttpClient code that you have that downloads the data from your server? I'm unsure where you're stuck. – Brandon Jan 18 '14 at 20:27
  • Hi brandon, thanks for your interest, I just added my HTTPClient up to the post. the HTTPClient doesn't download anything, it just ask my PHP script to retrieve my picture. Now I want to return this picture which is inside my PHP variable "$blob_data" to my Android device thanks HTTPClient and download the picture locally, to store it in my Android device. I hope I'm more clear. – Nizar B. Jan 18 '14 at 20:45
  • I think you want to add a `PHP` tag to this to get some help in adding the image to the HTTP response. – Brandon Jan 18 '14 at 20:50
  • Thanks, you're right and I've done it ;D – Nizar B. Jan 18 '14 at 20:55

3 Answers3

2

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" />
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
1

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

Community
  • 1
  • 1
adosaiguas
  • 1,331
  • 9
  • 13
1

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);
Shady Keshk
  • 540
  • 6
  • 16