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

时间:2022-12-02 21:14:51

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

你能告诉我如何将图像从URL转换成base64编码吗?

9 个解决方案

#1


412  

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

#2


99  

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,您将会遇到问题。

#3


23  

Use also this way to represent image in base64 encode format... find PHP function file_get_content and 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作为数据:“。file_mime_type。“base64_encoded字符串。在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.'">';

#4


7  

<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

刚刚用你的图片的URL - http://www.website.com/image.jpg替换了图片URL

#5


6  

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

如果您(出于某种原因)无法使用curl或file_get_contents,您可以使用以下方法:

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

#6


4  

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类型(从PHP文档中获得帮助)。

#7


2  

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

这里有一个使用旋度调用的例子。这比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);?>">  

#8


1  

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

#9


0  

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;

}

#1


412  

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

#2


99  

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,您将会遇到问题。

#3


23  

Use also this way to represent image in base64 encode format... find PHP function file_get_content and 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作为数据:“。file_mime_type。“base64_encoded字符串。在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.'">';

#4


7  

<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

刚刚用你的图片的URL - http://www.website.com/image.jpg替换了图片URL

#5


6  

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

如果您(出于某种原因)无法使用curl或file_get_contents,您可以使用以下方法:

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

#6


4  

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类型(从PHP文档中获得帮助)。

#7


2  

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

这里有一个使用旋度调用的例子。这比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);?>">  

#8


1  

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

#9


0  

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;

}