How to download an image from a URL using file_get_contents in PHP, resize the image using the GD library, and then encode the resized image as BASE64.

Here's an example of how to download an image from a URL using file_get_contents in PHP, resize the image using the GD library, and then encode the resized image as BASE64.php


// URL of the image you want to download and resize
$imageUrl = 'https://example.com/path/to/your/image.jpg';

// Download the image using file_get_contents
$imageData = file_get_contents($imageUrl);

if ($imageData === false) {
    echo 'Failed to download the image.';
    exit;
}

// Create an image resource from the downloaded image data
$originalImage = imagecreatefromstring($imageData);

if ($originalImage === false) {
    echo 'Failed to create image resource.';
    exit;
}

// Get the original image dimensions
$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);

// Calculate the new dimensions for the resized image
$newWidth = 200; // Replace with the desired width for the resized image
$newHeight = ($originalHeight / $originalWidth) * $newWidth;

// Create a new image resource for the resized image
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);

// Resize the image using GD
imagecopyresampled(
    $resizedImage, $originalImage,
    0, 0, 0, 0,
    $newWidth, $newHeight, $originalWidth, $originalHeight
);

// Start output buffering
ob_start();

// Save the resized image to output buffer
imagejpeg($resizedImage, null, 90); // Use 90 as the image quality (0-100)

// Get the contents of the output buffer
$resizedImageData = ob_get_contents();

// Clean up the output buffer
ob_end_clean();

// Encode the resized image as BASE64
$base64EncodedImage = base64_encode($resizedImageData);

// Free up memory
imagedestroy($originalImage);
imagedestroy($resizedImage);

echo 'Image successfully resized and encoded as BASE64: ' . $base64EncodedImage;

This script follows similar steps as the previous example but additionally encodes the resized image as BASE64. The encoded image data is stored in the $base64EncodedImage variable.

Please note that this example assumes the image is in JPEG format. If your images are in different formats, you may need to modify the image creation and saving functions accordingly. Additionally, ensure that the URL is accessible and that you have the necessary permissions to download and process the image.

Komentar

Postingan populer dari blog ini

WhatsApp Web login QR code in an HTML page using whatsapp-web.js

Node.js Telegram Bot API send an image with text

Add these security headers to your website