【问题标题】:php base64_encode image displayed on the site from external websitephp base64_encode 图像从外部网站显示在网站上
【发布时间】:2016-09-13 07:05:46
【问题描述】:

我从我的第一个网站获取内容并使用file_get_contents() 将其显示在我的另一个网站上,并且我正在使用preg_replace()preg_match() 按我想要的方式修改输出。

现在,有一些图片我想base64_encode(),但我一直在想怎么做?

如果我使用这行代码:

preg_match_all("/<img .*?(?=src)src=\"([^\"]+)\"/si", $fourth_content, $out)

我可以打印出所有图像src,但它无法对它们进行编码并将它们发送回 src。

有谁知道我如何做到这一点?

【问题讨论】:

  • 我认为您需要使用file_get_contents()src 获取图像文件内容,然后尝试对图像数据进行编码。

标签: php base64 preg-replace preg-match file-get-contents


【解决方案1】:

我建议分步思考。你必须做什么?

  1. 从远程 URL complete 获取 HTML
  2. 抓取每张图片complete
  3. 显示每张图片todo

你有图片的 URL,现在怎么办?你想遍历每张图片。

旁注:您要抓取的每个图像都意味着一个新的 HTTP 请求(下载)。这会迅速增加加载时间。想一想:这就是我想要的吗?如果是这样,那么让我们分解一下:

第 1 步

从 URL 获取 HTML。

<?php
    // Your URL
    $url = 'https://twitter.com/dogethedog';

    // Get HTML from your URL
    $data = file_get_contents($url);

第 2 步

抓取每张图片。

    // Grab every image source
    preg_match_all("/<img .*?(?=src)src=\"([^\"]+)\"/si", $data, $out);

步骤 3a

对我们获得的每个图像 URL 执行此操作。

    // Loop over every image source
    foreach($out[1] as $imageURL){

步骤 3b

从我们的 URL 下载图像数据。

对于要显示的 Base64 编码图像,我们还需要图像的内容类型。这可以通过 PHP 函数curl_getinfo() 抓取。

More info about Base64 images in HTML

More info about cURL, it's safer with e.g. images

         // Use cURL to fetch image data and image type
         // We need image type to be able to properly display jpg, png, gif, ...
         $ch        = curl_init($imageURL);

         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For https/ssl
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Standard cURL Option

         // Fetch cURL Content
         $imageData = curl_exec($ch);
         $imageType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

         // Close cURL Session
         curl_close($ch);

步骤 3c

现在我们有了数据和图像类型,正确渲染&lt;img&gt; 标签。

         // Image data gets to be fetched as BLOB, we need Base64
         $imageDataEncoded = base64_encode($imageData);

         // Build HTML <img> tag with proper type and base encoded image data
         ?>

         <img src="data:<?php print $imageType ?>;base64,<?php print $imageDataEncoded ?>" alt="Could not fetch image">

         <?php

    }

?>

【讨论】:

  • 谢谢约阿希姆!我会测试这个:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
  • 2012-12-03
  • 2013-03-13
  • 1970-01-01
  • 2013-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多