使用二进制数据显示图像的一部分

时间:2014-01-24 20:28:02

标签: php image-processing data-uri

我想知道是否可以使用file_get_contents显示图像的一部分。

目前我正在使用此代码显示图片而不显示其链接/位置

<img src="data:image/gif;base64,<?php echo base64_encode(file_get_contents($image)); ?> ">

有没有办法只使用file_get_contents显示1/3或1/2的图像?

2 个答案:

答案 0 :(得分:2)

为此,您需要对图像进行解码,裁剪和重新编码。在PHP中,您可以使用GD library来执行此操作,例如:

# load source image and get its size
$img = imagecreatefromgif( $image_file_name );
$width = imagesx( $img );
$height = imagesy( $img );

# create a copy showing only the top half of the image
$cropped = imagecreate( $width, $height / 2 );
imagecopy( $cropped, $img, 0,0, 0,0, $width, $height/2 );

# output image in GIF format emdebbed on the page
# XXX: GD doesn't seem to support output to string directly, but we can hack it
ob_start(); imagegif( $cropped ); $gif = ob_get_clean();
echo '<img src="data:image/gif;base64,', base64_encode( $gif ), '">';

# free the image objects once they're no longer needed
imagedestroy( $img );
imagedestroy( $cropped );

答案 1 :(得分:1)

浏览器不会解码部分图像。您可以使用各种CSS技术隐藏图像的其余区域,例如将图像包裹在DIV中,使用overflow:hidden设置CSS宽度+高度,或将其设置为CSS背景并设置该元素的尺寸

或者,您可以在canvas

中呈现它