Note that there are some explanatory texts on larger screens.

plurals
  1. PORotate and crop
    primarykey
    data
    text
    <p>I'm rotating and cropping a image with PHP, but I get the black border showing, I know you can change the background color, but I want to rotate and crop the image to fill the whole image. Basically something similar to <code>background-size: cover;</code> (left) in CSS versus <code>background-size: contain;</code> (right).</p> <p>See the image below, at right is what I got now, left is what I want to achieve. The number of degrees to rotate is dynamic and the image to be produced and the source-image are both square (200x200).</p> <p><img src="https://i.stack.imgur.com/7MRp7.png" alt="Illustration of problem"></p> <p><strong>EDIT:</strong> Here is my quick and dirty code:</p> <pre><code>$rotate = imagecreatefromjpeg($image); // part of code created by www.thewebhelp.com, modified $square_size = 200; $original_width = imagesx($rotate); $original_height = imagesy($rotate); if($original_width &gt; $original_height){ $new_height = $square_size; $new_width = $new_height*($original_width/$original_height); } if($original_height &gt; $original_width){ $new_width = $square_size; $new_height = $new_width*($original_height/$original_width); } if($original_height == $original_width){ $new_width = $square_size; $new_height = $square_size; } $new_width = round($new_width); $new_height = round($new_height); $smaller_image = imagecreatetruecolor($new_width, $new_height); $square_image = imagecreatetruecolor($square_size, $square_size); imagecopyresampled($smaller_image, $rotate, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height); if($new_width&gt;$new_height){ $difference = $new_width-$new_height; $half_difference = round($difference/2); imagecopyresampled($square_image, $smaller_image, 0-$half_difference+1, 0, 0, 0, $square_size+$difference, $square_size, $new_width, $new_height); } if($new_height&gt;$new_width){ $difference = $new_height-$new_width; $half_difference = round($difference/2); imagecopyresampled($square_image, $smaller_image, 0, 0-$half_difference+1, 0, 0, $square_size, $square_size+$difference, $new_width, $new_height); } if($new_height == $new_width){ imagecopyresampled($square_image, $smaller_image, 0, 0, 0, 0, $square_size, $square_size, $new_width, $new_height); } $degrees = rand(1,360); $square_image = imagerotate($square_image, $degrees, 0); imagejpeg($square_image,NULL,100); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload