Q. I possess both an image and a string, for example, 'Test' and image is 'sample.jpg'. Provide a PHP code that combines the string 'Test' with the image 'sample.jpg', merging them into a single image 'output.jpg'.
Solution:
<?php
// Function to merge text and image using default font
function mergeTextAndImage($text, $imagePath, $outputPath) {
// Load the image
$image = imagecreatefromjpeg($imagePath);
// Set the text color Red
$textColor = imagecolorallocate($image, 255, 0, 0);
// Set the font size
$fontSize = 5;
// Set the position to place the text on the image
$x = 10; // X-coordinate
$y = 30; // Y-coordinate
// Merge text onto the image using default font
imagestring($image, $fontSize, $x, $y, $text, $textColor);
// Save the merged image
imagejpeg($image, $outputPath); // Change this based on your image type
// Free up memory
imagedestroy($image);
}
// Example usage
$text = 'Test';
$imagePath = 'sample.jpg'; // Change this to the path of your image
$outputPath = 'output.jpg'; // Change this to the desired output path
mergeTextAndImage($text, $imagePath, $outputPath);
?>
<img src="output.jpg">
No comments:
Post a Comment