Ahmed Nader
Ahmed Nader

Reputation: 181

why I can't encode and decode base64 with java and php?

I encode Images on server with php and send the encoded strings to android via get request and decode it with java but It outputs bad base64 .

so I decided to check the base64 string on online checker but the image doesn't appear is the problem with the php encoding ?

here is the encoded image string :

aW1hZ2VzL21haW4vd3d3L25ldCAtIENvcHkucG5n

PHP::

<?php


require_once("config.php");

if(isset($_GET["m"])) {

    $dirname = "images/main/";
    $arr = array();

    $conn = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);

    if(!$conn) {
        echo "Error connecting to database";
        exit();
    }
    if($stmt = $conn->prepare("SELECT name_ FROM projects")) {
        $stmt->execute();
        $stmt->bind_result($n);
        //$stmt->store_result();
        $result = $stmt->get_result();
        if($result->num_rows == 0) {
            echo "No Projects";
            $stmt->close();
            $conn->close();
            exit();
        }else {
            while ($row = $result->fetch_assoc()) {
                $dirname = $dirname . $row["name_"] . "/";
                $images = glob($dirname . "*.*", GLOB_BRACE);
                foreach($images as $key => $image) {
                    $image = base64_encode($image);
                    //array_push($arr, $image);
                    $dirname = "images/main/";
                    echo $image;
                    echo "/n";
                    $image = "";
                }
            }
            //echo "hi";//json_encode($arr);
        }
    }

    $stmt->close();
    $conn->close();
    exit();

}

?>

ANDROID::

 @Override
    protected String doInBackground(String[] params) {
        String add = "http://10.0.2.2/wael/getimages.php?m=all";
        byte[] image = null;
        Bitmap real = null;
        String parsedString = "";
        BufferedReader bufferedReader = null;
        InputStream is = null;
        StringBuilder sb = null;
        HttpURLConnection httpConn = null;
        URLConnection conn = null;
        try {
            URL url = new URL(add);
            conn = url.openConnection();
            httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            is = httpConn.getInputStream();
            sb = new StringBuilder();
            String line;
            bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            bitmaps = new ArrayList<>();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\\n");

                //image = Base64.decode(line, Base64.NO_PADDING);
                //real = BitmapFactory.decodeByteArray(image, 0, image.length);
                //bitmaps.add(real);
                //image = null;
                //real = null;
            }
            String[] lines = sb.toString().split("\\n");
            for(String s: lines){
               image = Base64.decode(s, Base64.URL_SAFE);
                real = BitmapFactory.decodeByteArray(image, 0, image.length);
                bitmaps.add(real);
                image = null;
                real = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (httpConn != null) {
                    httpConn.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "done";
    }

HINT::

all types of modes in decoding using java are not working . for exmaple URL_SAFE , DEFAULT and etc arenot working all output the same bad base64

Upvotes: 0

Views: 1814

Answers (1)

dave
dave

Reputation: 64695

You aren't base64 encoding an image, you are base64 encoding the path to an image.

It's like if someone said "Send me a picture of the empire state building", and then you wrote them a letter that said "A picture of the empire state building".

For example, in your comment you said

the following is still not outputing an image aW1hZ2VzL21haW4vd3d3L25ldCAtIENvcHkucG5n

But if I do the following:

console.log(atob("aW1hZ2VzL21haW4vd3d3L25ldCAtIENvcHkucG5n"))

when you hit run you will see

images/main/www/net - Copy.png

Clearly, not the intended result.

In PHP, you would instead do something like this:

$image = file_get_contents($filename);
$b64_image_raw = base64_encode($im);      
$mime = mime_content_type($filetype)
$b64_image = "data:" . $mime . ";base64," . $b56_image_raw;

which will give you something like:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAdCAMAAABhTZc9AAAAP1BMVEU7V507V50AAAA7V507V507V53///9GYaP7/P33+Pvm6vPa4O2aqM3s7/bf5O+8xd6uutigrdBfd7BNZ6c+Wp9WPQrIAAAABXRSTlP0cwDze/4T5ZQAAABkSURBVCjP3c45DoAwDETRcUiclZ37n5UoFUUyEhIVv32yNTAyuX6TGIgbJwDRiqy36kuOGlNfj6StrvpZie7KdKmw+dGqUPUcbm5PP1d9FC6mmd6uVAtf9VcFUcAStTCCgULMDXttET4Wr4wGAAAAAElFTkSuQmCC

var image = document.createElement("img")
image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAdCAMAAABhTZc9AAAAP1BMVEU7V507V50AAAA7V507V507V53///9GYaP7/P33+Pvm6vPa4O2aqM3s7/bf5O+8xd6uutigrdBfd7BNZ6c+Wp9WPQrIAAAABXRSTlP0cwDze/4T5ZQAAABkSURBVCjP3c45DoAwDETRcUiclZ37n5UoFUUyEhIVv32yNTAyuX6TGIgbJwDRiqy36kuOGlNfj6StrvpZie7KdKmw+dGqUPUcbm5PP1d9FC6mmd6uVAtf9VcFUcAStTCCgULMDXttET4Wr4wGAAAAAElFTkSuQmCC";
document.getElementById("image").appendChild(image)
<div id="image"></div>

Upvotes: 1

Related Questions