使用 php 将图像 jpg 转换为 base 64

convert an image jpg to base 64 with php

我正在尝试将我的 wordpress 博客上的图片转换为 base64。

当我使用 this website 手动执行时,它有效。

但是当我在 PHp 中尝试时它不起作用:

$thePostThumb = get_the_post_thumbnail($postId, array(150,150));
background-image: url(\'data:image/jpg;base64,' . base64_encode($thePostThumb) . '\');

我也试过这个方法:

$type = pathinfo(get_the_post_thumbnail_url($postId, array(150,150)), PATHINFO_EXTENSION);
$data = file_get_contents(get_the_post_thumbnail_url($postId, array(150,150));
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data)

我知道正在检索缩略图 img,只是无法正常工作。 任何人都知道可能会发生什么。 我正在使用 xampp 并在本地机器上开发

这一定是可行的,刚刚在本地测试过:

$image = get_the_post_thumbnail_url($postID, array(150,150));
$ext = pathinfo($image, PATHINFO_EXTENSION);
echo 'data:image/' . $ext . ';base64,' . base64_encode(file_get_contents($image));