Skip to content
PHP Logo

How can imagecreatefromstring be used effectively in PHP to manipulate images?

To use imagecreatefromstring effectively in PHP to manipulate images, you can first read an image file into a string using file_get_contents, and then pass that string to imagecreatefromstring to create an image resource that can be manipulated using PHP's GD library functions.

php
// Read image file into a string
$imageString = file_get_contents('image.jpg');

// Create an image resource from the string
$image = imagecreatefromstring($imageString);

// Now you can manipulate the image using GD library functions
// For example, you can resize the image
$newWidth = 200;
$newHeight = 150;
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($image), imagesy($image));

// Output or save the manipulated image
header('Content-Type: image/jpeg');
imagejpeg($newImage, 'new_image.jpg');

// Free up memory
imagedestroy($image);
imagedestroy($newImage);