首页 > 解决方案 > 在 html标签中显示来自 curl 请求的图像

问题描述

我正在处理的网站的其中一个页面应该显示有关漫画的信息,例如它的封面图片。

我正在尝试显示通过 curl 请求获得的图像。

<?php
    if(isset($_GET['info'])) {
        $postedData = $_GET["info"]; //json object containing info about manga such as author/title etc.
        $info = json_decode($postedData, true);
        $mangacoverid = $info['im']; //id of the cover image that i'm getting from json object

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://cdn.mangaeden.com/mangasimg/" . $mangacoverid); //link of API i'm using and adding cover id to it
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $picture = curl_exec($ch);
        curl_close($ch);
        header('Content-type: image/jpeg');
        echo $picture; //displays image in browser
    }
        ?>

-Some 'mangacoverid' for testing purposes: ff/ff94bb880357b6b811bccbbfd3356c5ec41fbb184291323f0ed6a86a.jpg c1/c1b0173d8986681f23ecf5a69d26aa9dab4a04db4d40f99bed539198.jpg 0c/0cf6ebf78074e748ab2aeea3a0fcb9e0dd43040974c66e24fa46703f.jpg 5d/5dcfed2e033c2da62e7ac89367533ebbc344373c46a005e274a16785.png 18/18b1f0b13bccb594c6daf296c1f9b6dbd83783bb5ae63fe1716c9091.jpg 35/35bf6095212da882f5d2122fd547800ed993c58956ec39b5a2d52ad4.jpg

- 虽然我能够在页面中显示图像,但整个页面背景变为黑色,图像位于页面中间。(即样式=“边距:0px;背景:#0e0e0e;>”)。

我要做的是将图像插入 HTML 标记中,以便我可以将其放置在页面中的其他位置。

我尝试将带有'mangacoverid'的普通cdn链接放在标签中,但图像提供程序不允许热链接,它会引发403错误。

任何帮助真的很感激!

标签: phphtmlcurlphp-curl

解决方案


我测试了您的代码,当封面 ID 被硬编码时,它似乎可以正常工作。问题可能是通过查询参数传递的 JSON 没有被正确解析(由于 URL 编码)?

使用硬编码的封面 ID 是否可以正常工作?

文件image.php

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, sprintf('https://cdn.mangaeden.com/mangasimg/%s', $_GET['id']));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$picture = curl_exec($ch);
curl_close($ch);
header('Content-type: image/jpeg');
echo $picture;

在生成显示图像的页面的脚本中:

// Assuming $info holds the decoded json for the manga
echo(sprintf('<img src="image.php?id=%s>', $info['im']);

推荐阅读