PHP: convertire un'immagine in un URL di dati

PHP: convertire un'immagine in un URL di dati

In PHP è semplice convertire un'immagine in un URL di dati.

La soluzione è la seguente:


function base64_encode_image($filepath = '') {

    $data_url = '';

    if(empty($filepath)) {
        throw new InvalidArgumentException('You must provide a valid file path.');
    }

    if(!file_exists($filepath) || !is_readable($filepath)) {
        error_log("$filepath cannot be read.", 0);
        return $data_url;
    }

    $type = mime_content_type($filepath);

    if(strstr($type, 'image/') === false) {
        error_log("$filepath is not an image.", 0);
        return $data_url;
    }
    $img_binary = fread(fopen($filepath, 'r'), filesize($filepath));
    $data_url = 'data:' . $type . ';base64,' . base64_encode($img_binary);
    return $data_url;
}

Torna su