Engin Yapici
Engin Yapici

Reputation: 6154

How to get an image with php, resize and pass to Android

I have some images in a server and I would like to get those images with php, resize them and pass to my Android app. I use the below code to resize the images:

<?php
$image = imagecreatefromjpeg("test.jpg");

$original_image_width = imagesx($image);
$original_image_height = imagesy($image);

$resize_ratio = 0.5;

$resized_height = $original_image_height * $ratio;
$resized_width =  $original_image_width* $ratio;

$new_image = imagecreatetruecolor($resized_width, $resized_height);
$resized_image = imagecopyresampled($new_image, $image, 0, 0, 0, 0, $resized_width, $resized_height, $original_image_width, $original_image_height);
?>

I don't know how to pass the resized_image to android after that. I am using JSONObject and makeHttpRequest to pass string variables between my app and server and everything works fine. I tried to convert the resized_image to base64 string with following code:

<?php
$thumbnail = imagejpeg($resized_image);
$thumbnail_base64 = base64_encode($thumbnail);
?>

and pass it like that but I got "type java.lang.String cannot be converted to JSONObject" error.

What would be the best approach for me to pass it to my Android app? If anybody can show me how to pass base64 string I can handle the rest on Android side. Thanks in advance.

EDIT: My Android code is as below:

class getAllReports extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ShowAllReportsActivity.this);
        pDialog.setMessage(getResources().getString(R.string.getting_reports));
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... args) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        JSONObject json = jParser.makeHttpRequest(url_all_reports,
                "GET", params);
        Log.d("Reports: ", json.toString());

        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                reports = json.getJSONArray(TAG_REPORTS);

                for (int i = 0; i < reports.length(); i++) {
                    JSONObject c = reports.getJSONObject(i);

                    callNoArrayList.add(c.getString(TAG_CALL_NO));
                    yearArrayList.add(c.getString(TAG_YEAR));
                    modelArrayList.add(c.getString(TAG_MODEL));
                    tumbnailArrayList.add(c.getString(TAG_THUMBNAIL);
                }
            } else {
                Intent i = new Intent(getApplicationContext(),
                        MainActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
    protected void onPostExecute(String file_url) {
        long delayInMillis = 500;
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                pDialog.dismiss();
            }
        }, delayInMillis);
        runOnUiThread(new Runnable() {
            public void run() {
                populateList();
            }
        });
    }

}

TAGs and ArrayLists are initialized in main class.

Rest of my PHP code:

$db = new DB_CONNECT();
mysql_query('SET CHARACTER SET utf8');

$result = mysql_query("SELECT *FROM reports") or die(mysql_error());

if (mysql_num_rows($result) > 0) {
$response["reports"] = array();

while ($row = mysql_fetch_array($result)) {
    $report = array();
    $report["call_no"] = $row["call_no"];
    $report["year"] = $row["year"];
    $report["model"] = $row["model"];
    $report["thumbnail"] = $thumbnail_base64;
    array_push($response["reports"], $report);
}
$response["success"] = 1;

echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No reports found";

echo json_encode($response);
}

Upvotes: 0

Views: 1953

Answers (2)

Engin Yapici
Engin Yapici

Reputation: 6154

I solved the problem with a different approach. Instead of trying to pass $resized_image data on-the-fly I saved it in a temporary location first, base64 encoded it and passed it with JSONObject and everything worked fine. I deleted the temporary file from directory after I am done with it. Here is the PHP code to do it:

imagejpeg($resized_image, "tempimage.jpg", 75);
$file = file_get_contents("tempimage.jpg");
$base64_image = base64_encode($file);
unlink('tempimage.jpg');

I could easily pass this $base64_image without a problem with JSONObject. I guess it was adding some extra characters to the string when I tried to base64_encode the $resized_image on-the-fly and those characters caused parsing problems.

After I get the base64 encoded string on Android I decode and convert it to Bitmap with the following code:

    String mThumbnail = thumbnailArrayList.get(position);
    byte[] decodedString = Base64.decode(mThumbnail, Base64.DEFAULT);
    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    mReportImage.setImageBitmap(decodedByte);

Everything works smoothly with this approach.

Upvotes: 1

crazylpfan
crazylpfan

Reputation: 1088

Have you tried using json_encode? Something like this:

$msg= array(  
         'image' => $image
     );  
     echo json_encode($msg);

EDIT: Sorry, just saw the rest of your PHP code at the bottom.

EDIT 2: Maybe you could try setting the header?

header('Content-Type: application/json');

Upvotes: 0

Related Questions