php 如何将图像转换为 base64 编码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3967515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:36:13  来源:igfitidea点击:

How to convert an image to base64 encoding?

phpimagebase64

提问by Volatil3

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

你能指导我如何将图像从 URL 转换为 base64 编码吗?

回答by Ronny Sherer

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

回答by Pekka

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.

请记住,这会将数据放大 33%,并且文件大小超过memory_limit.

回答by Raju Rajotia Jangid

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

也使用这种方式以base64编码格式表示图像...找到PHP函数file_get_content,然后使用函数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.

并获得结果以将 str 准备为data:" . file_mime_type . " base64_encoded string. 在 img src 属性中使用它。请参阅以下代码,我可以为您提供帮助。

// 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.'">';

回答by yckart

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

以防万一您(无论出于何种原因)无法使用curlnor file_get_contents,您可以解决:

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

回答by GoldenGonaz

<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

刚刚用您的图片的网址替换了此处的图片网址 - http://www.website.com/image.jpg

回答by Reza Mamun

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

注意:文件的 Mime-Type 将自动添加(从这个PHP 文档中获取帮助)。

回答by Vivek

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

这是上传编码并保存到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>";

回答by JeanAlesi

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

这是一个使用 cURL 调用的示例。这比file_get_contents()函数更好。当然,使用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);?>">  

回答by Tayyab Hussain

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

您也可以通过 curl 执行此操作,只需要一个图像文件的路径并将其传递给下面给出的函数。

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;

}