Display a part of image using binary data
I wonder if it is possible to display a part of image using file_get_contents
.
Currently I'm using this code to display the image without revealing its link/location
<img src="data:image/gif;base64,<?php echo base64_encode(file_get_contents($image)); ?> ">
Is there a way to just display 1/3 or 1/2 of the image using file_get_contents
?
To do this, you need to decode, crop and re-encode the image. In PHP, you can use the GD library to do this, eg:
# 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 );
The browser will not decode partial images. You can use various CSS techniques to hide the remaining areas of the image, such as wrapping your image in a DIV, setting CSS width + height with overflow:hidden
, or setting it as a CSS background and setting the dimensions of that element.
Alternately, you can render it in canvas
.
上一篇: 连接字符串或使用多个回显参数:哪个更快?
下一篇: 使用二进制数据显示图像的一部分