Wednesday 27 July 2016

Encode Image in PHP as a Data Source

Use this simple php function to encode image into a data source for easy inline of the image data. This method will make the image load faster in webpage.

function encodeImage($filepath) {
    $filecontents = file_get_contents($filepath);
    $base64 = base64_encode($filecontents);
    $imagetype = exif_imagetype($filepath);
    $mime = image_type_to_mime_type($imagetype);
    return "data:$mime;base64,$base64";
}

No comments:

Post a Comment