Download, Crop and save image in a specific directory is one of the most irritated task sometime I have to do. But as a web developer I got some skills to tackle this hectic task. 🙂
I have created a php script that download, crop and save image from url. I just have to pass image url in the input field, set dimensions and image will crop and save in the folder.
Also read
- How to upload multiple images in PHP and store in Mysql
- How to display images from folder in PHP
- jQuery Zoom Image on Hover
In this tutorial I am going to share the basic idea behind that code with you guys. If you are following my blog you people know that I write my blog post keeping PHP beginners in my mind. So lets start with basics. I will use some built-in image functions of PHP which are listed below.
Function | Description |
---|---|
imagecreatefromjpeg($filename) | Create a new image from url or file |
imagejpeg($image, $to, $quality) | Output JPEG file from the given image |
imagepng($image, $to, $quality, $filters) | Output or save PNG file from given image |
imagegif($image, $to) | creates the GIF file |
imagecropauto($image, $mode, $threshold, $color) | Automatically crops an image according to the given mode. Modes are IMG_CROP_DEFAULT, IMG_CROP_TRANSPARENT, IMG_CROP_BLACK, IMG_CROP_WHITE, IMG_CROP_SIDES, IMG_CROP_THRESHOLD |
imagesx($image) | Return the width of the given image |
imagesy($image) | Return the height of the given image |
imagecrop($image, $rect) | Crops an image to the given rectangular area and returns the resulting image. The given image is not modified. |
imagedestroy() | Free memory associated with image |
I will be using following image throughout my examples.
1 2 3 |
<?php $image = imagecreatefromjpeg("https://www.wdb24.com/wp-content/uploads/2018/02/php-curl-get.jpg"); ?> |
Create JPEG:
1 2 3 |
<?php imagejpeg($image, "my-image-1.jpg");?> |
Create PNG:
1 2 3 |
<?php imagepng($image, 'my-image-2.png'); ?> |
Create GIF:
1 2 3 |
<?php imagegif($image,'my-image-3.gif'); ?> |
Auto Crop Image:
1 2 3 4 5 6 |
<?php $cropImageAuto = imagecropauto($image, IMG_CROP_THRESHOLD, null, 16777215); imagejpeg($cropImageAuto, "my-image-4.jpg"); ?> |
Auto Crop Manually:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $image2 = imagecrop($image, ['x' => 150, 'y' => 60, 'width' => 400, 'height' => 300]); if ($image2 !== FALSE) { imagejpeg($image2, 'crop-image.jpg'); imagedestroy($image2); } imagedestroy($image); ?> |