【问题标题】:Responsive fake/placeholder image响应式假/占位符图像
【发布时间】:2016-02-18 15:56:57
【问题描述】:

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

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

我尝试了类似以下的图像标记,但由于height: auto,它不起作用。关于那个奇怪的 src 看看this

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

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

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

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

【问题讨论】:

  • 你有没有考虑过使用placehold.it之类的东西?
  • &lt;img src="http://placehold.it/200x150" alt="" /&gt;
  • 你只是用颜色填充“空白”图像是什么? &lt;img style="background:#ccc"&gt;
  • 嘿,谢谢大家 ;) 从来没有听说过 placehold.it ... 看起来很棒。问题是这是一个wordpress插件。所以它应该在没有互联网连接的本地机器上运行。但看起来该服务完全符合我的需要
  • 如果有帮助,可以使用WP_Image_Editor在WordPress中动态调整图片大小。

标签: php html css responsive-images


【解决方案1】:

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

<?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="" />

【讨论】:

  • 请记住,虽然这可能适用于您安装的 WordPress,但那是因为您有可用的 GD 库。其他人可能有 ImageMagick,或者根本没有库,如果您要分发此代码,而不是仅将其用于已知环境,您可能需要考虑这些可能性。 (这就是我建议尽可能使用 WP_Image_Editor 的原因;它透明地使用它可以找到的任何图像库。)
  • 是的,这很好 x_x。但是如果这个插件被发布,可能会有成千上万的东西不能完美地工作......虽然它已经很神奇了,但它还远远没有为公众做好准备。也许我应该试试你的解决方案;)
【解决方案2】:

您为什么不使用 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');
?>

【讨论】:

  • 从头开始创建图像需要 GB 库:$my_img = imagecreate( 200, 150 );imagepng($my_img);imagedestroy($my_img);
  • 问题是 1x1px 大小的图像在响应式环境中的行为不像 200x150px 大小的图像
猜你喜欢
  • 2017-12-18
  • 2015-07-15
  • 1970-01-01
  • 2016-03-18
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
  • 2013-04-28
相关资源
最近更新 更多