366

How can I convert an image from a URL to Base64 encoding?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Volatil3
  • 14,253
  • 38
  • 134
  • 263
  • 4
    What do you want to do this for? – Pekka Oct 19 '10 at 10:46
  • 9
    to embed it in src attribute of Img tag – Volatil3 Oct 20 '10 at 03:31
  • 6
    This is an old thread, but for completeness' sake: It makes a lot of sense to encode images, especially small ones (under 1k), for use in css. This way you save one request, which would take longer and might be even larger, due to overhead. – arminrosu Oct 31 '12 at 12:46

9 Answers9

731

I think that it should be:

$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
kenorb
  • 155,785
  • 88
  • 678
  • 743
Ronny Sherer
  • 8,349
  • 1
  • 22
  • 9
  • 12
    It depends on what you need the image for. If it's as an inline URL, this is the way to go. It's not identical with mere base64 encoding though. – Pekka Jul 31 '13 at 13:21
  • Excellent tip, now i will create be a function to edit file upload, or a revert move_uploaded_file(), thanks – Vinicius De Jesus Mar 28 '20 at 13:54
  • 2
    This worked like a charm! Been stuck with DomPDF image for a while now, thank you so much for this! – Suomynona May 02 '21 at 23:21
  • 3
    The `pathinfo($path, PATHINFO_EXTENSION)` part might not work with **SVG** images. Just change the last line to ```php $base64 = 'data:image/svg+xml;base64,' . base64_encode($data); ``` – Eddie C. Jan 26 '22 at 17:01
  • 4
    You should use mime_content_type() to get mimetype instead of extension (not reliable) – Loenix Aug 04 '22 at 08:30
  • 1
    @EddieC. - Good tip regards SVG. Would it be more robust if the script queried the mimetype rather then the extension? – AutoBaker Feb 24 '23 at 08:24
  • $type = \Illuminate\Support\Str::of($path)->explode('.')->last() – Hossien Salamhe Jun 26 '23 at 10:55
144

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
48

Also use this way to represent an image in Base64-encoded format...

Find the PHP function file_get_content and next use the function base64_encode.

And get the result to prepare str as data:" . file_mime_type . " base64_encoded string. Use it in the img src attribute. The following code ma be helpful:

// 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.'">';
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Raju Ram
  • 943
  • 9
  • 15
  • 1
    If failed to find function mime_content_type just add the function from svogal from http://php.net/manual/en/function.mime-content-type.php – mario ruiz Dec 10 '13 at 20:00
20

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);
yckart
  • 32,460
  • 9
  • 122
  • 129
15

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).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Reza Mamun
  • 5,991
  • 1
  • 43
  • 42
14
<img src="data:image/png;base64,<?php echo base64_encode(file_get_contents("IMAGE URL HERE")) ?>">

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

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
GoldenGonaz
  • 1,116
  • 2
  • 17
  • 42
3

Here is the code for uploading to encode and save it to a MySQL database:

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>";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vivek
  • 1,446
  • 18
  • 27
2

You can also do this via cURL. You just 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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tayyab Hussain
  • 1,658
  • 1
  • 18
  • 21
1

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

<?php
    $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);?>">
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JeanAlesi
  • 478
  • 3
  • 17
  • 2
    `curl` is absolutely not "better" than `file_get_contents` unless you need to add additional data to the call ex. authentication. Moreover, `file_get_contents` is gonna fallback to getting a local file's contents when possible, thus not making a useless network call. – Hissvard Dec 16 '19 at 09:23