Image resizing

Hello,

The following code is image resizing code
The code below only considers the width
What changes do I need to make so that it takes both width and height into account?

$maxDim = 260; // $maxWidth = 260; $maxHeinght = 113;
$file_name = $_FILES['urun_resim']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
	$target_filename = $file_name;
	$ratio = $width/$height;
	if( $ratio > 1) {
		$new_width = $maxDim;
		$new_height = $maxDim/$ratio;
	} else {
		$new_width = $maxDim*$ratio;
		$new_height = $maxDim;
	}
	$src = imagecreatefromstring( file_get_contents( $file_name ) );
	$dst = imagecreatetruecolor( $new_width, $new_height );
	imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
	imagedestroy( $src );
	imagepng( $dst, $target_filename ); // adjust format as needed
	imagedestroy( $dst );

	$base64image = base64_encode(file_get_contents($target_filename));
	printf('<img src="data:image/png;base64,%s" />', $base64image);
}else{ // If the picture width is smaller than maxDim
	$target_filename = $file_name;
	$src = imagecreatefromstring( file_get_contents( $file_name ) );
	$dst = imagecreatetruecolor( $width, $height );
	imagecopyresampled( $dst, $src, 0, 0, 0, 0, $width, $height, $width, $height );
	imagedestroy( $src );
	imagepng( $dst, $target_filename ); // adjust format as needed
	imagedestroy( $dst );

	$base64image = base64_encode(file_get_contents($target_filename));
	printf('<img src="data:image/png;base64,%s" />', $base64image);
}

I did something like below, but I don’t know how well I did it, can you take a look?

$maxWidth = 260; 
$maxHeinght = 113;
$file_name = $_FILES['urun_resim']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
$target_filename = $file_name;

		$x_ratio = $maxWidth  / $width;  
		$y_ratio = $maxHeinght / $height;  

		if (($width <= $maxWidth) and ($height <= $maxHeinght)){  
			$new_width  = $width;  
			$new_height = $height;  
		}  
		else if (($x_ratio * $height) < $maxHeinght){  
			$new_width  = $maxWidth;  
			$new_height = ceil($x_ratio * $height);  
		}  
		else {  
			$new_width  = ceil($y_ratio * $width);  
			$new_height = $maxHeinght;  
		}

$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );

//imagealphablending($dst, false); // DO YOU NEED THIS?
//imagesavealpha($dst, true); // DO YOU NEED THIS?
//$transparent = imagecolorallocatealpha($dst, 255, 255, 0, 127); // DO YOU NEED THIS?
//imagefilledrectangle($dst, 0, 0, $new_width, $new_height, $transparent); // DO YOU NEED THIS?

imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );

$base64image = base64_encode(file_get_contents($target_filename));
printf('<img src="data:image/png;base64,%s" />', $base64image);

I don’t do it this way any longer, but the following might help you?

   // Check if the file was uploaded successfully
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $uploadedFile = $_FILES['image'];

        // Validate the file (e.g., file size, type, etc.)
        $maxFileSize = 25 * 1024 * 1024; // 25 MB
        $allowedFileTypes = ['image/jpeg', 'image/png'];

        if ($uploadedFile['size'] > $maxFileSize) {
            echo json_encode(['error' => 'File size is too large.']);
            exit();
        }

        if (!in_array($uploadedFile['type'], $allowedFileTypes)) {
            echo json_encode(['error' => 'Invalid file type.']);
            exit();
        }

        // Move the uploaded file to the desired destination
        $destinationDirectory = '../assets/canvas_images/';
        $saveDirectory = '/assets/canvas_images/';
        $destinationFilename = time() . '_' . basename($uploadedFile['name']);
        $destinationPath = $destinationDirectory . $destinationFilename;

        if (move_uploaded_file($uploadedFile['tmp_name'], $destinationPath)) {
            // Load the image
            $image = imagecreatefromjpeg($destinationPath);

            // Get the original dimensions
            $original_width = imagesx($image);
            $original_height = imagesy($image);

            // Calculate the new dimensions
            $new_width = 1200;
            $new_height = 800;
            $scale = min($new_width / $original_width, $new_height / $original_height);
            $width = intval($original_width * $scale);
            $height = intval($original_height * $scale);

            // Create a new image with the new dimensions
            $new_image = imagecreatetruecolor($width, $height);

            // Copy and resize the original image to the new image
            imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, $original_width, $original_height);
            // Save the new image
            imagejpeg($new_image, $destinationPath, 100);

            $savePath = $saveDirectory . $destinationFilename;
            // Prepare the SQL INSERT statement
            $sql = "INSERT INTO lego_trivia (points, question, answer, canvas_images) VALUES (:points, :question, :answer, :canvas_images)";
            $stmt = $pdo->prepare($sql);

            // Bind the values to the placeholders
            $stmt->bindValue(':points', $points, PDO::PARAM_INT);
            $stmt->bindValue(':question', $question);
            $stmt->bindValue(':answer', $answer);
            $stmt->bindValue(':canvas_images', $savePath);

            // Execute the prepared statement
            $insertSuccess = $stmt->execute();

I do it this way now and find it much easier →

use Intervention\Image\ImageManagerStatic as Image;

// Check if the form was submitted with POST method
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the input and textarea values
    $category = $_POST['category'] ?? null;
    $question = $_POST['question'] ?? null;
    $answer = $_POST['answer'] ?? null;
    $points = $_POST['points'] ?? null;
    // Validate input and textarea values as needed
    // ...

    // Check if the file was uploaded successfully
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $uploadedFile = $_FILES['image'];

        // Validate the file (e.g., file size, type, etc.)
        $maxFileSize = 56 * 1024 * 1024; // 25 MB
        $allowedFileTypes = ['image/jpeg', 'image/png'];

        if ($uploadedFile['size'] > $maxFileSize) {
            echo json_encode(['error' => 'File size is too large.']);
            exit();
        }

        if (!in_array($uploadedFile['type'], $allowedFileTypes)) {
            echo json_encode(['error' => 'Invalid file type.']);
            exit();
        }

        // Move the uploaded file to the desired destination
        $destinationDirectory = '../assets/canvas_images/';
        $saveDirectory = '/assets/canvas_images/';
        $destinationFilename = time() . '_' . basename($uploadedFile['name']);
        $destinationPath = $destinationDirectory . $destinationFilename;

        if (move_uploaded_file($uploadedFile['tmp_name'], $destinationPath)) {
            // Load the image
            $image = Image::make($destinationPath);

            // Resize the image to a width of 1200 and constrain aspect ratio (auto height)
            $image->resize(1200, null, function ($constraint) {
                $constraint->aspectRatio();
            });

            // Save the resized image
            $image->save($destinationPath);

            $savePath = $saveDirectory . $destinationFilename;

            // Prepare the SQL INSERT statement
            $sql = "INSERT INTO canyousolve (points, question, answer, canvas_images, category) VALUES (:points, :question, :answer, :canvas_images, :category)";
            $stmt = $pdo->prepare($sql);

            // Bind the values to the placeholders
            $stmt->bindValue(':points', $points, PDO::PARAM_INT);
            $stmt->bindValue(':question', $question);
            $stmt->bindValue(':answer', $answer);
            $stmt->bindValue(':canvas_images', $savePath);
            $stmt->bindParam(':category', $category);
            // Execute the prepared statement
            $insertSuccess = $stmt->execute();

I find using \ImageManagerStatic library is easier and a little more secure.

1 Like

Thank you
It is very important to be safe

The code in the second message // I activated the code in the slashes, it fixed the color problem in gif images.

What I want to do is to upload the images without stretching them like a tire, without exceeding the maximum width and height, while maintaining the uploaded image ratio.

And I want to save images as base64 in database not server because this is not album and its size is thumbnails.

Sponsor our Newsletter | Privacy Policy | Terms of Service