Skip to content
Advertisement

base64 image not displaying in html

I am trying to display my base64 image that I converted in my php file. However the image in my html appears as the generic image placeholder for when an image is not available or existent. In case anyone is wondering I am trying to display images that belong to a specific web page form. However I have many forms and when I click on one of them I want to be able to see the images associated.

I have gotten this far: my PHP file looks like this:

$imageDate = date_format($currentdate, 'YmdHis');
$path = 'C:/Temp/MgrReportUploads';
$type = pathinfo($path, PATHINFO_EXTENSION);

$files = glob($path.
    '/'.$imageDate.
    '_*');

if (!empty($files)) {
    foreach($files as $image) {

        $vals['encodedImages'] = 'data:image/'.$type.
        ';base64,'.base64_encode($image);

    }
}

echo json_encode ( $vals); response looks like this on the Network Tab returnedImages: {,…}

images: "data:image/jpg;base64,QzovVGVtcC9NZ3JSZXBvcnRVcGxvYWRzLzIwMTkxMTA4MTM0MzM5X2plZGkxLmpwZw=="

js File // callback variables on the form and Images

onSuccess: function(data) {

    var imgList = document.querySelector('#imageLst'); //div
    var img = document.createElement("img");
    img.setAttribute("src", data.encodedImages);
    imgList.append(img);
}

Advertisement

Answer

Change base64_encode($image) to base64_encode(file_get_contents($image))

glob returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

You have to pass file content not file path to base64_encode

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement