是否可以在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插件,它也应该在没有互联网连接的情况下本地运行。最好的解决方案是没有外部服务。
这是我提出的解决方案(这种大小的完全透明图像):
<?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="" />
与其使用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');
?>