在 PHP 内将图像的一部分发送给客户端

Send portion of an image to client in PHP

您好,我的 PHP 服务器上有一个巨大的图像,代表网络游戏中的地图。 我只需要客户请求来获取该图像的一小部分。客户端请求无法加载整个图像,因为: 1) 会让服务器窒息
2)我不想让客户知道整个地图的样子

imagecopy功能能满足我的需要吗?在那种情况下我不知道如何使用它......我有这个片段:

<?php        
    // Create image instances
    $src = imagecreatefromgif('images\map.gif');
    $dest = imagecreatetruecolor($mapVisibleWidth, $mapVisibleHeight); 

    // Copy
    imagecopy($dest, $src, 0, 0, x, y, mapVisibleWidth, mapVisibleWidth);                

    // Output and free from memory
    header('Content-Type: image/gif');
    imagegif($dest);

    imagedestroy($dest);
    imagedestroy($src);

    ?> 

谢谢!

我没有任何大地图图像或你有的东西..

但举个例子,我刚刚在 google 上搜索并得到了一张满足您需要的随机图片。

第 1 步:

使用 imagecreatefrompng.png 文件生成图像

$srcp = imagecreatefrompng("http://www.clker.com/cliparts/O/f/g/g/S/T/curly-frame-hi.png");

您可以指向任何具有 png 图像的url

第 2 步:

设置要创建的图像的大小

$destp = imagecreate(150, 150);

第 3 步:

使用您的自定义设置制作副本

图像复制重采样($destp, $srcp, 0, 0, 8, 8, 150, 150, 8, 8);

第 4 步:

设置header类型并生成

header('Content-type: image/png');
imagepng($destp);

因此您的代码将是

<?php
    $srcp = imagecreatefrompng("http://www.clker.com/cliparts/O/f/g/g/S/T/curly-frame-hi.png");
    $destp = imagecreate(150, 150);
    imagecopyresampled ($destp, $srcp, 0, 0, 8, 8, 150, 150, 8, 8);
    header('Content-type: image/png');
    imagepng($destp);
?>

注:

  1. 对于其他格式、大小和图像,您可以按照相同的方法进行少量修改。

  2. 通过这种方式,用户甚至无法通过图片路径或右键单击打开完整图片,是的,如您所想,它是安全的。

更新:

由于OP需要显示标题、标题等,

由于函数本身会默认创建 headers 和 html 元素,因此您无需担心。

但如果你想这样做,你可以使用类似 iframe 的东西,其中 php 页面本身可以加载到你想要的任何页面。

这是他的简短示例。

将以下文件保留为 source.php

<?php
    $srcp = imagecreatefrompng("http://www.clker.com/cliparts/O/f/g/g/S/T/curly-frame-hi.png");
    $destp = imagecreate(150, 150);
    imagecopyresampled ($destp, $srcp, 0, 0, 8, 8, 150, 150, 8, 8);
    header('Content-type: image/png');
    imagepng($destp);
?>

并将页面设置为 display.html

你可以像这样制作一个iframe

<!DOCTYPE html>
<html>
<head>
    <title>Image Display Viewer</title>
</head>
 <style type="text/css" media="screen">
        body,
        html {
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        * {
            padding: 0;
            margin: 0;
        }

        iframe {
            width: 960px;
            height: 100%;
            overflow: hidden;
            border: none;
        }
    </style>
<body>
<iframe src="source.php" scrolling="0"></iframe>
</body>
</html>

注意: 虽然 iframe 不是一个好主意,但用户仍然无法看到图像的任何其他部分。这意味着你仍然是安全的:)