During PHP image processing, there are times when we need to flip an image (e.g., vertically or horizontally) and want to display the processed result directly on the webpage rather than saving it to a file and accessing it later. Additionally, if we want to manage the output—such as caching it or handling the output stream—ob_start() proves to be very useful.
This article demonstrates how to use both ob_start() and imageflip() to flip an image and output the result directly to the browser. At the same time, it allows us to cache the image content as a variable (useful for CDNs or debugging).
Make sure your PHP environment has the GD library enabled, as it's essential for image processing. You can check this using the terminal or within code with phpinfo().
<?php
phpinfo();
?>
You can either allow users to upload an image or use an image that already exists on the server. In this example, we'll use a sample image from the server:
$imagePath = 'https://m66.net/images/sample.jpg'; // Sample image from m66.net domain
Here's the complete sample code. It flips the image horizontally and outputs the result directly to the browser. Meanwhile, the output buffer can be used for further processing:
<?php
// Specify image path
$imageUrl = 'https://m66.net/images/sample.jpg';
<p>// Get image content<br>
$imageData = file_get_contents($imageUrl);<br>
if (!$imageData) {<br>
die('Unable to retrieve image content');<br>
}</p>
<p>// Create image resource<br>
$srcImage = imagecreatefromstring($imageData);<br>
if (!$srcImage) {<br>
die('Failed to create image');<br>
}</p>
<p>// Flip image (horizontally)<br>
imageflip($srcImage, IMG_FLIP_HORIZONTAL);</p>
<p>// Start output buffering<br>
ob_start();</p>
<p>// Set content type<br>
header('Content-Type: image/jpeg');</p>
<p>// Output image<br>
imagejpeg($srcImage);</p>
<p>// Get buffered content<br>
$imageOutput = ob_get_contents();</p>
<p>// Clean and close buffer<br>
ob_end_clean();</p>
<p>// Output image content to webpage<br>
echo $imageOutput;</p>
<p>// Destroy image resource<br>
imagedestroy($srcImage);<br>
?><br>
ob_start() initiates output buffering.
All echo or imagejpeg() output is captured instead of being sent directly to the browser.
ob_get_contents() retrieves the content from the buffer (in this case, the binary image data).
ob_end_clean() clears and closes the buffer without automatically outputting its content.
Allows flexible output control, such as saving to a cache file or applying further processing.
Avoids header errors caused by premature output.
You can save $imageOutput as a cache file or upload it to a CDN.
Be mindful of memory usage if the image is large.
It's not recommended to use ob_start() in scripts that have already sent output.