4

是否可以在 html 中伪造一个看起来像真实但不存在的空图像?

例如,我有一个响应列,其中应该是一个 200x150px 的图像(它被设置样式:width: 100%; height: auto;因为它的响应)......但是如果没有图像,它应该被放置一个占位符,该占位符完全伪造一个真正的 200x150px 大小的图像的大小有。

我尝试了如下所示的图像标签,但它因此不起作用height: auto。关于那个奇怪的 src 看看这个

<img src="//:0" alt="" width="200" height="150" />

可以用php生成一个空的png吗?

<img src="fake.php?s=200x150" alt="" />

编辑:有些人提到了服务placehold.it。基本上这正是我需要的(在大多数情况下绝对足够),但因为这是一个 WordPress 插件,它也应该在没有互联网连接的情况下在本地运行。最好是没有外部服务的解决方案。

4

2 回答 2

2

这是我想出的解决方案(该尺寸的完全透明图像):

<?php

    // Image size
    $imageWidth = is_numeric( $_GET[ 'w' ] ) ? $_GET[ 'w' ] : 0;
    $imageHeight = is_numeric( $_GET[ 'h' ] ) ? $_GET[ 'h' ] : 0;

    // Header
    header ('Content-Type: image/png');

    // Create Image
    $image = imagecreatetruecolor( $imageWidth, $imageHeight );
    imagesavealpha( $image, true );
    $color = imagecolorallocatealpha($image, 0, 0, 0, 127);
    imagefill($image, 0, 0, $color);

    // Ouput
    imagepng( $image );
    imagedestroy( $image );

?>

也可以用颜色填充图像:

<?php

    // Image size
    $imageWidth = is_numeric( $_GET[ 'w' ] ) ? $_GET[ 'w' ] : 0;
    $imageHeight = is_numeric( $_GET[ 'h' ] ) ? $_GET[ 'h' ] : 0;

    // Header
    header ('Content-Type: image/png');

    // Create Image
    $image = imagecreatetruecolor( $imageWidth, $imageHeight );
    imagesavealpha( $image, true );
    $color = imagecolorallocatealpha($image, 180, 180, 180, 0);
    imagefill($image, 0, 0, $color);

    $text_color = imagecolorallocatealpha( $image, 255, 255, 255, 50 );
    imagestring($image, 1, 5, 5,  $imageWidth . ' x ' . $imageHeight, $text_color);

    // Ouput
    imagepng( $image );
    imagedestroy( $image );

?>

用法是:

<img src="placeholder.php?w=350&h=250" alt="" />
于 2015-11-17T11:01:48.317 回答
0

与其使用 php 来提供“假”图像,不如使用透明的 1px x 1px png 文件的占位符图像?

无论如何,要回答您的问题,您可以使用 php 提供图像服务:

<?php
//redefine the header
header("Content-type: image/png");
//send the image content
readfile('/path/of/a/png/image.png');
?>
于 2015-11-17T10:19:29.437 回答