Mon Jun 29 2020

Imagick

PHP Scripting1815 views

File Name: php-imagick.php

<!DOCTYPE html>
<html>
	<head>
		<title>File upload using Imagick</title>
	</head>
	<body>
		<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
			Select File: <input type="file" required name="imageUp" accept="image/*" />
			Eneter file name: <input type="text" required name="fileName" />
			<button type="submit">Upload</button>
		</form>
		<?php
		if(isset($_FILES['imageUp']['name'])){

			/* Get the extension of the file */
			$extension = strtolower(substr($_FILES["imageUp"]["name"], strrpos($_FILES["imageUp"]["name"], '.')+1));
			$dir = "images";
			$filename = $_POST["fileName"].".".$extension;
			$filepath = $dir."/".$filename;
			
			/* Creates an Imagick instance for image */
			$image = new Imagick($_FILES["imageUp"]["tmp_name"]);
			
			/* Changes the size of the image */
			$image->thumbnailImage(500,500,true);
			
			/* Upload an image to by specified filename */
			if($image->writeImage($filepath)) {
				
				/* Get the image dimension */
				list($width, $height) = getimagesize($filepath);
				$handlers = array('jpg'  => 'imagecreatefromjpeg', 
						'jpeg' => 'imagecreatefromjpeg', 
						'png'  => 'imagecreatefrompng', 
						'gif'  => 'imagecreatefromgif', 
						'bmp' => 'imagecreatefromwbmp'
				);
				
				/* Find image extension */
				if ($handler = $handlers[$extension]) {
					$image = $handler($filepath);
					$filesave = $dir."/".$_POST["fileName"].".jpg";
					
					/* Create a new true color image */
					$tn = imagecreatetruecolor($width, $height);
					
					/* Allocate a color for an image */
					$white = imagecolorallocatealpha($tn, 255, 255, 255,127);
					
					/* Fill image with color */
					imagefill($tn, 0, 0, $white);
					
					/* Copy and resize part of the image with resampling */
					imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $width, $height) ;
					
					/* Publish image */
					header('Content-Type: image/jpeg');
					imagejpeg($tn, $filesave, 100);
					
					/* Destroy an image */
					imagedestroy($tn);
					
					/* Delete all the images without .jpg extension */
					if($extension != "jpg")
						unlink($filepath);
				}
				echo "File uploaded successfully!";
			}
			else
				echo "Fail to upload!";
		}
		?>
	</body>
</html>



/* Output */
Choose File
Enter file name

File uploaded successfully!

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.