0

I want to select image from my gallery, and then upload it to my php server. Then the php have to save my image in a directory in my server. But i have a error at loading image to my server and I don't know why. This is my code from Android:

import java.io.ByteArrayOutputStream;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sourcey.modeloUsuarios.JSONParser;
import com.sourcey.modeloUsuarios.R;

@SuppressLint("NewApi")
public class CargarImagenes extends Activity {
ProgressDialog prgDialog;
String encodedString;
RequestParams params = new RequestParams();
String imgPath, fileName;
Bitmap bitmap;
private static int RESULT_LOAD_IMG = 1;

private static String url_imagen_complejo = "https://www.myhosting.com/upload_image.php";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cargar_imagenes);
    prgDialog = new ProgressDialog(this);
    // Set Cancelable as False
    prgDialog.setCancelable(false);
}

public void loadImagefromGallery(View view) {
    // Create intent to Open Image applications like Gallery, Google Photos
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}

// When Image is selected from Gallery
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                && null != data) {
            // Get the Image from data

            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgPath = cursor.getString(columnIndex);
            cursor.close();
            ImageView imgView = (ImageView) findViewById(R.id.imgView);
            // Set the Image in ImageView
            imgView.setImageBitmap(BitmapFactory
                    .decodeFile(imgPath));
            // Get the Image's file name
            String fileNameSegments[] = imgPath.split("/");
            fileName = fileNameSegments[fileNameSegments.length - 1];
            // Put file name in Async Http Post Param which will used in Php web app
            params.put("filename", fileName);

        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

}

// When Upload button is clicked
public void uploadImage(View v) {
    // When Image is selected from Gallery
    if (imgPath != null && !imgPath.isEmpty()) {
        prgDialog.setMessage("Converting Image to Binary Data");
        prgDialog.show();
        // Convert image to String using Base64
        encodeImagetoString();
        // When Image is not selected from Gallery
    } else {
        Toast.makeText(
                getApplicationContext(),
                "You must select image from gallery before you try to upload",
                Toast.LENGTH_LONG).show();
    }
}

// AsyncTask - To convert Image to String
public void encodeImagetoString() {
    new AsyncTask<Void, Void, String>() {

        protected void onPreExecute() {

        };

        @Override
        protected String doInBackground(Void... params) {
            BitmapFactory.Options options = null;
            options = new BitmapFactory.Options();
            options.inSampleSize = 3;
            bitmap = BitmapFactory.decodeFile(imgPath,
                    options);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            // Must compress the Image to reduce image size to make upload easy
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
            byte[] byte_arr = stream.toByteArray();
            // Encode Image to String
            encodedString = Base64.encodeToString(byte_arr, 0);
            HashMap<String, String> imagen = new HashMap<>();
            imagen.put("ikea", encodedString);
            String cadena = JSONParser.performPostCall(url_imagen_complejo, imagen);
            System.out.println(cadena);
            return "";
        }

        @Override
        protected void onPostExecute(String msg) {

            prgDialog.dismiss();
        }
    }.execute(null, null, null);
}




@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    // Dismiss the progress bar when application is closed
    if (prgDialog != null) {
        prgDialog.dismiss();
    }
}
}

activity activity_cargar_imagen.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ImageView
    android:id="@+id/imgView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >
</ImageView>

<Button
    android:id="@+id/buttonLoadPicture"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight="0"
    android:onClick="loadImagefromGallery"
    android:text="Load Picture" >
</Button>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:onClick="uploadImage"
    android:text="Upload" />

</LinearLayout>

And this is my php file:

<?php

/**
* BulletProof
*
* A single class PHP-library for secure image uploading.
*
* PHP support 5.3+
*
* @package     BulletProof
* @version     2.0.0
* @author      Samayo  /@sama_io
* @link        https://github.com/samayo/bulletproof
* @license     MIT
*/
namespace BulletProof;
class Image implements \ArrayAccess
{
/**
 * @var string The new image name, to be provided or will be generated.
 */
protected $name;
/**
 * @var int The image width in pixels
 */
protected $width;
/**
 * @var int The image height in pixels
 */
protected $height;
/**
 * @var string The image mime type (extension)
 */
protected $mime;
/**
 * @var string The full image path (dir + image + mime)
 */
protected $fullPath;
/**
 * @var string The folder or image storage location
 */
protected $location;
/**
 * @var array A json format of all information about an image
 */
protected $serialize = array();
/**
 * @var array The min and max image size allowed for upload (in bytes)
 */
protected $size = array(100, 50000);
/**
 * @var array The max height and width image allowed
 */
protected $dimensions = array(500, 5000);
/**
 * @var array The mime types allowed for upload
 */
protected $mimeTypes = array("jpeg", "png", "gif");
/**
 * @var array list of known image types
 */
protected $imageMimes = array(
    1 => "gif", "jpeg", "png", "swf", "psd",
    "bmp", "tiff", "tiff", "jpc", "jp2", "jpx",
    "jb2", "swc", "iff", "wbmp", "xbm", "ico"
);
/**
 * @var array storage for the $_FILES global array
 */
private $_files = array();
/**
 * @var string storage for any errors
 */
private $error = "";
/**
 * @param array $_files represents the $_FILES array passed as dependancy
 */
public function __construct(array $_files = [])
{
    $this->_files = $_files;
}
/**
 * Gets the real image mime type
 *
 * @param $tmp_name string The upload tmp directory
 *
 * @return bool|string
 */
protected function getImageMime($tmp_name)
{
    if (isset($this->imageMimes[exif_imagetype($tmp_name)])) {
        return $this->imageMimes [exif_imagetype($tmp_name)];
    }
    return false;
}
/**
 * array offset \ArrayAccess
 * unused
 */
public function offsetSet($offset, $value){}
public function offsetExists($offset){}
public function offsetUnset($offset){}
/**
 * Gets array value \ArrayAccess
 *
 * @param mixed $offset
 *
 * @return bool|mixed
 */
public function offsetGet($offset)
{
    if ($offset == "error") {
        return $this->error;
    }
    if (isset($this->_files[$offset]) && file_exists($this->_files[$offset]["tmp_name"])) {
        $this->_files = $this->_files[$offset];
        return true;
    }

    return false;
}
/**
 * Renames image
 *
 * @param null $isNameGiven if null, image will be auto-generated
 *
 * @return $this
 */
public function setName($isNameProvided = null)
{
    if ($isNameProvided) {
        $this->name = filter_var($isNameProvided, FILTER_SANITIZE_STRING);
    }

    return $this;
}
/**
 * Define a mime type for uploading
 *
 * @param array $fileTypes
 *
 * @return $this
 */
public function setMime(array $fileTypes)
{
    $this->mimeTypes = $fileTypes;
    return $this;
}
/**
 * Define a min and max image size for uploading
 *
 * @param $min int minimum value in bytes
 * @param $max int maximum value in bytes
 *
 * @return $this
 */
public function setSize($min, $max)
{
    $this->size = array($min, $max);
    return $this;
}
/**
 * Creates a location for upload storage
 *
 * @param $dir string the folder name to create
 * @param int $permission chmod permission
 *
 * @return $this
 */
public function setLocation($dir = "imagenes", $permission = 0666)
{
    if (!file_exists($dir) && !is_dir($dir) && !$this->location) {
        $createFolder = @mkdir("" . $dir, (int) $permission, true);
        if (!$createFolder) {
            $this->error = "Folder " . $dir . " could not be created";
            return;
        }
    }
    $this->location = $dir;
    return $this;
}
/**
 * Sets acceptable max image height and width
 *
 * @param $maxWidth int max width value
 * @param $maxHeight int max height value
 *
 * @return $this
 */
public function setDimension($maxWidth, $maxHeight)
{
    $this->dimensions = array($maxWidth, $maxHeight);
    return $this;
}
/**
 * Returns the image name
 *
 * @return string
 */
public function getName()
{
    if (!$this->name) {
       return  uniqid(true) . "_" . str_shuffle(implode(range("e", "q")));
    }
    return $this->name;
}
/**
 * Returns the full path of the image ex "location/image.mime"
 *
 * @return string
 */
public function getFullPath()
{
    $this->fullPath = $this->location . "/" . $this->name . "." . $this->mime;
    return $this->fullPath;
}
/**
 * Returns the image size in bytes
 *
 * @return int
 */
public function getSize()
{
    return (int) $this->_files["size"];
}
/**
 * Returns the image height in pixels
 *
 * @return int
 */
public function getHeight()
{
    if ($this->height != null) {
        return $this->height;
    }
    list(, $height) = getImageSize($this->_files["tmp_name"]); 
    return $height;
}
/**
 * Returns the image width
 *
 * @return int
 */
public function getWidth()
{
    if ($this->width != null) {
        return $this->width;
    }
    list($width) = getImageSize($this->_files["tmp_name"]); 
    return $width;
}
/**
 * Returns the storage / folder name
 *
 * @return string
 */
public function getLocation()
{
    if(!$this->location){
        $this->setLocation(); 
    }
    return $this->location; 
}
/**
 * Returns a JSON format of the image width, height, name, mime ...
 *
 * @return string
 */
public function getJson()
{
    return json_encode($this->serialize);
}
/**
 * Returns the image mime type
 *
 * @return string
 */
public function getMime()
{
    return $this->mime;
}
/**
 * Returns error string or false if no errors occurred
 *
 * @return string|bool
 */
public function getError(){
    return $this->error != "" ? $this->error : false;
}
/**
 * Checks for the common upload errors
 *
 * @param $e int error constant
 */
protected function uploadErrors($e)
{
    $errors = array(
        UPLOAD_ERR_OK           => "",
        UPLOAD_ERR_INI_SIZE     => "Image is larger than the specified amount set by the server",
        UPLOAD_ERR_FORM_SIZE    => "Image is larger than the specified amount specified by browser",
        UPLOAD_ERR_PARTIAL      => "Image could not be fully uploaded. Please try again later",
        UPLOAD_ERR_NO_FILE      => "Image is not found",
        UPLOAD_ERR_NO_TMP_DIR   => "Can't write to disk, due to server configuration ( No tmp dir found )",
        UPLOAD_ERR_CANT_WRITE   => "Failed to write file to disk. Please check you file permissions",
        UPLOAD_ERR_EXTENSION    => "A PHP extension has halted this file upload process"
    );
    return $errors[$e];
}
/**
 * Main upload method.
 * This is where all the monkey business happens
 *
 * @return $this|bool
 */
public function upload()
{
    /* modify variable names for convenience */
    $image = $this; 
    $files = $this->_files;
    /* initialize image properties */
    $image->name     = $image->getName();
    $image->width    = $image->getWidth();
    $image->height   = $image->getHeight(); 
    $image->location = $image->getLocation();
    /* get image sizes */
    list($minSize, $maxSize) = $image->size;
    /* check for common upload errors */
    if($image->error = $image->uploadErrors($files["error"])){
        return ;
    }
    /* check image for valid mime types and return mime */
    $image->mime = $image->getImageMime($files["tmp_name"]);
    /* validate image mime type */
    if (!in_array($image->mime, $image->mimeTypes)) {
        $ext = implode(", ", $image->mimeTypes);
        $image->error = "Invalid File! Only ($ext) image types are allowed";
        return ;
    }     
    /* check image size based on the settings */
    if ($files["size"] < $minSize || $files["size"] > $maxSize) {
        $min = intval($minSize / 1000) ?: 1; $max = intval($maxSize / 1000);

        $image->error = "Image size should be atleast more than min: $min and less than max: $max kb";
        return ;
    }
    /* check image dimension */
    list($allowedHeight, $allowedWidth) = $image->dimensions;
    if ($image->height > $allowedHeight || $image->width > $allowedWidth) {
        $image->error = "Image height/width should be less than ' $allowedHeight \ $allowedWidth ' pixels";
        return ;
    }
    if($image->height < 4 || $image->width < 4){
        $image->error = "Invalid! Image height/width is too small or maybe corrupted"; 
        return ;
    }

    /* set and get folder name */
    $image->fullPath = $image->location. "/" . $image->name . "." . $image->mime;
    /* gather image info for json storage */ 
    $image->serialize = array(
        "name"     => $image->name,
        "mime"     => $image->mime,
        "height"   => $image->height,
        "width"    => $image->width,
        "size"     => $files["size"],
        "location" => $image->location,
        "fullpath" => $image->fullPath
    );
    if ($image->error === "") {
        $moveUpload = $image->moveUploadedFile($files["tmp_name"], $image->fullPath);
        if (false !== $moveUpload) {
            return $image;
        }
    }

    $image->error = "Upload failed, Unknown error occured";
    return false;
}
/**
 * Final upload method to be called, isolated for testing purposes
 *
 * @param $tmp_name int the temporary location of the image file
 * @param $destination int upload destination
 *
 * @return bool
 */
public function moveUploadedFile($tmp_name, $destination)
{
    return move_uploaded_file($tmp_name, $destination);
}
}

EDIT: May be the error is here:

require_once  "path/to/bulletproof.php";

$image = new Bulletproof\Image($_FILES);

if($image["ikea"]){
$upload = $image->upload(); 

if($upload){
    // OK
}else{
    echo $image["error"]; 
}
}

The post method works greats. Thanks for helping me!

samayo
  • 16,163
  • 12
  • 91
  • 106
Federick Jons
  • 93
  • 1
  • 13
  • Many people just encode the file contents to base64 format, then receive the contents as a regular string in the server side. PHP have built in `base64_decode` function that can be used to return the encoded string to its original content. Then you can just create a file with the contents as `file_put_contents("my_image.jpg", base64_decode($contents));` – CarlosCarucce May 24 '16 at 17:35
  • So... How can you use it in my code? – Federick Jons May 24 '16 at 17:57
  • @FederickJons What is the error you are getting? – samayo May 25 '16 at 11:04
  • I don't know because nothing return. May be I need to add POST in another php and reference to the php – Federick Jons May 25 '16 at 11:38
  • @FederickJons Where is your HTML form? – samayo May 25 '16 at 14:04
  • I uploaded by my android app! no html form – Federick Jons May 26 '16 at 01:36
  • @samayo How can I change your code to use with my android java code?. See my code pls – Federick Jons May 26 '16 at 01:37
  • You need to have a form name called 'ikea' or change that name to what you have in your android form. The name 'ikea' is just there as a dummy placeholder, if you are going to use it, then your android form must be aware of it. Sadly I don't know about Java/android to see what you should change. – samayo May 26 '16 at 06:22
  • @FederickJons Did that work for you? – samayo May 26 '16 at 11:27
  • No. I don't know how to use it – Federick Jons May 26 '16 at 11:28
  • @FederickJons Do maybe `var_dump($image); ` right below `$image = new Bulletproof\Image($_FILES);` and let me know – samayo May 26 '16 at 11:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/113025/discussion-between-federick-jons-and-samayo). – Federick Jons May 26 '16 at 11:51

0 Answers0