[php] How to convert an image to base64 encoding?

Can you please guide me how can I convert an image from a URL to base64 encoding?

This question is related to php image base64

The answer is


Use also this way to represent image in base64 encode format... find PHP function file_get_content and next to use function base64_encode

and get result to prepare str as data:" . file_mime_type . " base64_encoded string. Use it in img src attribute. see following code can I help for you.

// A few settings
$img_file = 'raju.jpg';

// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;

// Echo out a sample image
echo '<img src="'.$src.'">';

Here is an example using a cURL call.. This is better than the file_get_contents() function. Of course, use base64_encode()

$url = "http://example.com";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
?>

<img src="data:image/png;base64,<?php echo base64_encode($output);?>">  

You can also do this via curl, just you need a path to an image file and pass it to the function given below..

public static function getImageDataFromUrl($url)
{
    $urlParts = pathinfo($url);
    $extension = $urlParts['extension'];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $base64 = 'data:image/' . $extension . ';base64,' . base64_encode($response);
    return $base64;

}

Here is the code for upload to encode and save it to the MySQL

if (!isset($_GET["getfile"])) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Error: " . $_FILES["file"]["error"] . "<br>";
    } else {
        move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);

        $bin_string = file_get_contents($_FILES["file"]["name"]);
        $hex_string = base64_encode($bin_string);
        $mysqli = mysqli_init();

        if (!$mysqli->real_connect('localhost', 'root', '', 'arihant')) {
            die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
        }

        $mysqli->query("INSERT INTO upload(image) VALUES ('" . $hex_string . "')");
    }
}

For showing the image use this

echo "<img src='data:image/jpeg;base64, $image' width=300>";

Just in case you are (for whatever reason) unable to use curl nor file_get_contents, you can work around:

$img = imagecreatefrompng('...');
ob_start();
imagepng($img);
$bin = ob_get_clean();
$b64 = base64_encode($bin);

Easy:

$imagedata = file_get_contents("/path/to/image.jpg");
             // alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

bear in mind that this will enlarge the data by 33%, and you'll have problems with files whose size exceed your memory_limit.


Very simple and to be commonly used:

function getDataURI($imagePath) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $type = $finfo->file($imagePath);
    return 'data:'.$type.';base64,'.base64_encode(file_get_contents($imagePath));
}

//Use the above function like below:
echo '<img src="'.getDataURI('./images/my-file.svg').'" alt="">';
echo '<img src="'.getDataURI('./images/my-file.png').'" alt="">';

Note: The Mime-Type of the file will be added automatically (taking help from this PHP documentation).


<img src="data:image/png;base64,<?php echo base64_encode(file_get_contents("IMAGE URL HERE")) ?>">

I was trying to use this resource but kept getting an error, I found the code above worked perfectly.

Just replaced IMAGE URL HERE with the URL of your image - http://www.website.com/image.jpg


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to base64

How to convert an Image to base64 string in java? How to convert file to base64 in JavaScript? How to convert Base64 String to javascript file object like as from file input form? How can I encode a string to Base64 in Swift? ReadFile in Base64 Nodejs Base64: java.lang.IllegalArgumentException: Illegal character Converting file into Base64String and back again Convert base64 string to image How to encode text to base64 in python Convert base64 string to ArrayBuffer