How do I rotate an image in PHP and actually see the rotation in the browser?
How can I rotate an image in PHP? was last modified: April 19th, 2023 by
1 Answers
Best Answer
Here is how you do it. Simple and easy to do. Take this code an play around with it. I am using Bootstrap for the forms.
<?php include_once('header.php'); include_once('error.php'); //-90 turns to the right 90 turns to the left and 0 flips it upside down $rand=rand(1,1000); //$file1='uploadtest/max-flash.jpg'; $file1='uploadtest/flash.png'; $newfilename=''; if(isset($_POST['rotate'])){ $rot=$_POST['rotate']; if(exif_imagetype($file1) != IMAGETYPE_JPEG){ $newfile=rand(1,1000); $newfilename='uploadtest/'.$newfile.'.png'; $source = imagecreatefrompng($file1); $rotate = imagerotate($source, $rot, 0); //header('Content-Type: image/png'); imagejpeg($rotate, $newfilename); //print_r('Image saved successfully.'); // Destroy loaded image to free memory imagedestroy($source); echo 'Not a JPEG image'; }else{ $newfile=rand(1,1000); $newfilename='uploadtest/'.$newfile.'.jpg'; $source = imagecreatefromjpeg($file1); $rotate = imagerotate($source, $rot, 0); //header('Content-Type: image/jpg'); imagepng($rotate, $newfilename); print_r('Image saved successfully.'); imagedestroy($source); echo 'Not a PNG image'; } if( !rename($newfilename, $file1) ) { echo "File can't be renamed!"; } else { echo "File has been renamed!"; } echo '<br/><hr/>'; echo '<img src="'.$file1.'?p='.$rand.'" width="400" />'; }else{ echo '<img src="'.$file1.'?p='.$rand.'" width="400" />'; echo '<div class="alert alert-warning">'.$file1.'</div>'; } ?> <form method="post"> <select name="rotate" onchange="this.form.submit()" class="form-control"> <option>Select</option> <option value="-90">Turn Right</option> <option value="90">Turn Left</option> <option value="180">Flip</option> </select> </form> <?php include_once('footer.php');?>
Answer for How can I rotate an image in PHP? was last modified: April 19th, 2023 by