<form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" value="Upload"> </form>
Note that the form's enctype attribute must be set to "multipart/form-data" to support file uploads.
$uploadDir = 'uploads/'; mkdir($uploadDir);
After creating the directory, we can proceed to handle the image upload.
if ($_FILES['image']['error'] == UPLOAD_ERR_OK) { // Image uploaded successfully } else { // Image upload failed echo 'Image upload failed, please try again!'; }
Note that the $_FILES['image']['error'] variable holds the error code. If it equals UPLOAD_ERR_OK, the upload was successful.
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . $_FILES['image']['name'])) { // Image moved successfully } else { // Image move failed echo 'Image move failed, please try again!'; }
$srcImage = imagecreatefromjpeg($uploadDir . $_FILES['image']['name']); $dstImage = imagecreatetruecolor(200, 200); imagecopyresized($dstImage, $srcImage, 0, 0, 0, 0, 200, 200, imagesx($srcImage), imagesy($srcImage)); imagejpeg($dstImage, $uploadDir . 'thumbnail.jpg'); imagedestroy($srcImage); imagedestroy($dstImage);
In this example, we use the imagecreatefromjpeg function to create an image resource from the original image. Then, we use imagecreatetruecolor to create a target image of the specified size. Finally, we use imagecopyresized to perform the resizing operation.
$srcImage = imagecreatefromjpeg($uploadDir . $_FILES['image']['name']); $dstImage = imagecreatetruecolor(200, 200); imagecopyresampled($dstImage, $srcImage, 0, 0, 100, 100, 200, 200, 200, 200); imagejpeg($dstImage, $uploadDir . 'cropped.jpg'); imagedestroy($srcImage); imagedestroy($dstImage);
Unlike resizing, for cropping, we use the imagecopyresampled function. The first four parameters represent the starting coordinates for the target image, while the last four parameters represent the coordinates and size of the source image.
$srcImage = imagecreatefromjpeg($uploadDir . $_FILES['image']['name']); $watermarkImage = imagecreatefrompng('watermark.png'); imagecopy($srcImage, $watermarkImage, 10, 10, 0, 0, imagesx($watermarkImage), imagesy($watermarkImage)); imagejpeg($srcImage, $uploadDir . 'watermarked.jpg'); imagedestroy($srcImage); imagedestroy($watermarkImage);
We use the imagecreatefromjpeg function to create the original image resource and the imagecreatefrompng function to create the watermark image resource. Then, we use imagecopy to overlay the watermark onto the original image. Finally, we save the image with the watermark using the imagejpeg function.