将 PHP 数组中 URL 处的图像编码为 Base64

Encode Images at URL in PHP Array as Base64

这是我的代码,我正在尝试获取图像内容并将其编码为 base64,但我一直以 URL 作为 base64 字符串结束。

最后我从 API 中获取图像作为数组,我需要将它们转码为 Base64 以存储在本地数据库中。

这是基于 Gravity Forms API、Wordpress、PHP、mySQL、(LAMP) 等

<?php
$images = array();
    $body = array();
    $imagesDecoded = array();
    $imgUrls = array(
                    '1' => 'bg.jpg',
                    '2' => 'meeting.jpg',
                    '3' => 'testimonial.jpg',
                    '4' => 'works.jpg',
                );

$imgUrls = array_map(function($el) {
    return 'http://orlandojoes.co.uk/rimos/images/' . $el;
}, $imgUrls);

print'<pre>';
print_r($imgUrls);
print'</pre>';

foreach ($imgUrls as $image) {
    $data = file_get_contents($imgUrls);
    $data = base64_encode($imgUrls);
    array_push($body, $data);

}

print '<pre>';
print_r ($body);
print '<pre>';

foreach ($body as $bodyimage) {
    $dataDec = base64_decode($bodyimage);
    array_push($imagesDecoded, $dataDec);
}
print '<pre>';
print_r ($imagesDecoded);
print '<pre>';

这是我 运行 现在这段代码的输出:

Array
(
    [ptSignature] => http://orlandojoes.co.uk/rimos/images/bg.jpg
    [pSignature] => http://orlandojoes.co.uk/rimos/images/meeting.jpg
    [witness1Signature] => http://orlandojoes.co.uk/rimos/images/testimonial.jpg
    [witness2Signature] => http://orlandojoes.co.uk/rimos/images/works.jpg
)
Array
(
    [0] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy9iZy5qcGc=
    [1] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy9tZWV0aW5nLmpwZw==
    [2] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy90ZXN0aW1vbmlhbC5qcGc=
    [3] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy93b3Jrcy5qcGc=
)
Array
(
    [0] => http://orlandojoes.co.uk/rimos/images/bg.jpg
    [1] => http://orlandojoes.co.uk/rimos/images/meeting.jpg
    [2] => http://orlandojoes.co.uk/rimos/images/testimonial.jpg
    [3] => http://orlandojoes.co.uk/rimos/images/works.jpg
)

您的代码中有两个错误。

$data = file_get_contents($imgUrls); // This is an array of URLs
$data = base64_encode($imgUrls); // You encode the URLs here!

应该是:

$data = file_get_contents($image); // $image instead of $imgUrls
$data = base64_encode($data); // $data instead of $imgUrls

或者简单地说:

$data = base64_encode(file_get_contents($image));

旁注,您的代码中不需要 array_push(),通常只有在您想一次推送多个项目时才需要。因此,您可以将其更改为:

$body[] = $data;