script for cropping images - php

I have many (about 1000) images (printscreens), and I need to crop these images (all cropped images are in the same region in the full image).
How can I do this in php? Or maybe GIMP is supporting some macro scripts to do this?
Thanks in advance.

Except using GD, as Greg and n1313 proposed, you can also use ImageMagick for that, e.g. similar to Greg's solution, but with
$original_image = new Imagick($file->getRealPath());
$dest_image = $original_image->clone();
$dest_image->cropImage($width, $height, $x, $y);
$dest_image->writeImage('./resized/' . $file->getFilename());
You might check for exceptions when creating the new image (i.e. image cannot be opened) or returned false on cropImage and writeImage (image cannot be cropped or cannot be written).

You can do it in PHP using the GD image functions.
Your script might look something like this (not tested):
$it = new RecursiveDirectoryIterator('./screenshots');
foreach ($it as $file)
{
if (!preg_match('/\.jpe?g$/i', $file->getFilename()))
continue;
$src = imagecreatefromjpeg($file->getRealPath());
$dest = imagecreatetruecolor(1000, 1000);
imagecopyresampled($desc, $src, 0, 0, X_OFFSET, Y_OFFSET, 1000, 1000, WIDTH, HEIGHT);
imagejpeg($dest, './resized/' . $file->getFilename());
}

To do this with PHP you'll need a GD image manipulation library. Then you can use imagecopy() function to crop you image and many others GD functions to manipulate the image in whatever way you need.

Related

Merge multiple pictures into one

Let's suppose I want to create a face generator, where I would design several pictures for face form, ears, noses, mouth, hair. Given a combination of those pictures how can I create a new picture in PHP? For instance, a simplified version:
There is face1.png, face2.png, nose1.png and nose2.png. How could I programmatically merge face1.png with nose2.png, so the result picture would hold content from both picture?
You've basically got three options: GD, Cairo or ImageMagic. I'd recommend using the Imagick class if it's available. If not, ImageMagick through PHP system calls. If that's not available, GD will probably suffice.
It depends on your server configuration, which of these are available and which would require additional packages to be installed.
There's a very simple example in the Imagick documentation of combining images: https://secure.php.net/manual/en/imagick.compositeimage.php
I also found this example for GD:
Merge two PNG images with PHP GD library
There is a function named imagecopy. This function overrides a part of the destination image using a source image. The given part is specified as parameters. Before you tell me that this does not solve your problem, I have to add that the pixels in the destination picture will not be overriden by the pixels of the source picture if the pixels are transparent. You need to use imagealphablending and imagesavealpha on the source picture, like this:
public static function experimental($images, $width, $height, $dest = null) {
$index = 0;
if ($dest === null) {
$dest = $images[$index++];
}
while ($index < count($images)) {
imagealphablending($images[$index], true);
imagesavealpha($images[$index], true );
imagecopy($dest, $images[$index++], 0, 0, 0, 0, $width, $height);
}
return $dest;
}
If we have these two pictures:
The result will be this:
You really want make it with PHP?
Ok.
1) You can use GD library for image processing.
2) You can use imagemagic PHP wrapper -- imagic.
But I think you should use canvas on client side. And for saving result you can send base64 png image representation of canvas (or separated layers/pictures) to backend.

How to put a watermark text across the whole image in diagonal position?

I have connected my Google Drive with my website and im getting images in this format: https://googledrive.com/host/{$GoogleID}. What i want to do is to add a text (not image) watermark to all the images im getting from Google Drive. I already tried with:
http://php.net/manual/en/image.examples.merged-watermark.php
http://phpimageworkshop.com/tutorial/1/adding-watermark.html
Both of them dosent work for me or i cant get them to work i dont know why. I will give an example for an image url: https://googledrive.com/host/0B9eVkF94eohMRlBQVENRWE5mc2c
I have also tried the code from this answer, but it dosent work as well. I guess the problem should be that the files i'm getting from Google Drive are not with the file extention and maybe this cause the problem. This is only my guess...
UPDATE:
i managed to show the photo on the website, but how to put the text in diagonal possition across all the photo like this
try to read image with file_get_contents or fopen and create image from string.
$im = imagecreatefromstring(file_get_contents("image url"));
and then use this example: http://php.net/manual/en/image.examples.merged-watermark.php
Thanks to #Durim Jusaj for helping me out with this one and finally i got the answer after a lot of searching and dealing with a lot of problems i will share my knowledge with u guys. So i will post the code and i will explain what is the code doing.
First thing first. Include this function in your file. This function is finding the center of the image. I havent wrote it i found it in the php docs under the comments so maybe it can be done without it or this function can be modified to be better written.
function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
{
// retrieve boundingbox
$bbox = imagettfbbox($size, $angle, $fontfile, $text);
// calculate deviation
$dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0; // deviation left-right
$dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0; // deviation top-bottom
// new pivotpoint
$px = $x-$dx;
$py = $y-$dy;
return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
}
Load the image you want to apply the watermark to. I'm using Google Drive to extract my photos so thats why im using the file_get_contents, if you are the case like mine then use this, BUT otherwise use what is common and if your picture have extension like .jpg or .png you can use imagecreatefromjpeg or imagecreatefrompng. So it should be something like that $im = imagecreatefromjpeg('photo.jpeg'); for example.
$im = imagecreatefromstring(file_get_contents("https://drive.google.com/uc?id=" . $v['GoogleID']));
After that we need to calculate the position of watermark so we want the watermark to be in the center and to auto adjust its size based on the size of the photo. So on the first like we store all the attributes of the image to array. Second and third lines we calculate where is the center of the image (for me dividing it by 2.2 worked great, you can change this if u want to adjust the position. Last line is the size of the watermark according to the size of the image. This is very important as the watermark will be small or very big if u have images with different sizes.
list($width, $height, $type, $attr) = getimagesize("https://drive.google.com/uc?id=" . $v['GoogleID']);
$width = $width / 2.2;
$height = $height / 2.2;
$size = ($width + $height) / 4;
Set the content-type
header('Content-Type: image/png');
Create the image. I dont know why it should be done twice, but im following the php manual.
$im = imagecreatefromstring(file_get_contents("https://drive.google.com/uc?id=" . $v['GoogleID']));
Create some colors. So, if you want your watermark to be transparent (like mine) you have to use imagecolorallocatealpha, otherwise use imagecolorallocate. Last parameter is the transparency. You can google every function name for more info from the php doc.
$black = imagecolorallocatealpha($im, 0, 0, 0, 100);
The text to draw. Simple as that. Write what you want your text to be.
$text = 'nima.bg';
Replace path by your own font path. Put a font in your server so the code can take it (if you dont have already).
$font = 'fonts/ParsekCyrillic.ttf';
Adding all together. Basically you are creating the final image with the water mark with this function. The magic ;)
imagettftext_cr($im, $size, 20, $width, $height, $black, $font, $text);
Now this is the tricky part! If you want to just display the image without saving it to your server you can simply copy and paste this code, but the website will load very slow if you have more then 2-3 images. So, what i suggest you to do it to save the final images to your server and then display it. I know you will have duplicates, but this is the best choice i think.
ob_start();
imagepng($im);
$image = ob_get_contents();
ob_end_clean();
imagedestroy($im);
echo "<img src='data:image/png;base64," . base64_encode($image) . "'>";
}
OR you can save the images to your server and then display them which is much much faster. The best thing you can do is to process all the images create them with the watermark and then display them (so you have them ready to be show when a visitor visit your website).
imagepng($im, 'photo_stamp.png');
imagedestroy($im);
And the final result for me was that.
UPDATE: As of 2017 you can extract the image using this link 'https://drive.google.com/uc?id=(GoogleID)' or you can just use the 'webContentLink' property of the Google_DriveFile Object (it will give you the same link).

PHP GD - imagerotate for a jpeg image is not working

Title says JPEG. But I tried PNG. It didn't work.
GD supports imagerotate function.
if (function_exists('imagerotate')) {
echo "test";
}
It outputs the word test. So i assume I have imagerotate function.
$im = imagecreatetruecolor($width + 10, $height + 10);
...
I did some image porcess. I can see the processed image without any problem. But i want to rotate the final image. So i did the following.
imagerotate($im,180,0);
imagepng($im,$png,9);
imagedestroy($im);
But I am still getting the image without rotation.
I even just tried to rotate a image without doing any process. It didn't work too.
You need to assign the rotated image to another variable before create the png.
$rotatedImage = imagerotate($im,180,0);
imagepng($rotatedImage,$png,9);
imagedestroy($rotatedImage);

Image uploading concept in PHP

how to take image from one folder and rename and re-size the images and move to another folder?
I need to get image from one folder and rename and re-size the same image and move into another folder using php
You will most likely be using gd for resizing the images.
Here is a pretty crappy, but hopefully useful code sample. In this case, $originalName is the name given in the $_FILES array's tmp_name position. I am resizing to a width of 1200 in this case, with the height adapting according to such width. You might (and most likely will) not desire this behavior. This is just some ugly code I used in some courses I taught about 3 years ago, I don't have the newer samples in this computer so you will have to get used to the idea :)
$newDir is where the file will be located. by calling imagejpeg or imagepng and passing the filename as second argument, it means to the function that you wish to save the image in that location.
if ($type == 'image/jpeg') {
$original = imagecreatefromjpeg($originalName);
}
else {
$original = imagecreatefrompng($originalName);
}
$width = imagesx($original);
$height = imagesy($original);
//prepare for creation of image with width of 1000
$new_height = floor($height * (1200 / $width));
// create the 1200 width image
$tmp_img = imagecreatetruecolor(1200, $new_height);
// copy and resize old image into new image
imagecopyresized($tmp_img, $original, 0, 0, 0, 0,
1200, $new_height, $width, $height);
//create a random and unique name to identify (here it isn't that random ;)
$newDir = '/this/is/some/directory/and/filename.';
if ($type == 'image/jpeg') {
imagejpeg($tmp_img, $newDir."jpg");
}
else {
imagepng($tmp_img, $newDir."png");
}
Many file system functions are already built-in with PHP (e.g. rename), and you'll find most of what you need to resize images by using the GD library here.
There are libraries available in PHP for image resize.
Here are some useful links you may like.
http://www.fliquidstudios.com/2009/05/07/resizing-images-in-php-with-gd-and-imagick/
http://php.net/manual/en/book.image.php
PHP/GD - Cropping and Resizing Images
http://net.tutsplus.com/tutorials/php/image-resizing-made-easy-with-php/
Use imagick http://php.net/manual/en/imagick.resizeimage.php
If I were you I would write a PE using a diffent language (one that you might be best used to) to adjust anything of the given image then just feel free to phpexec it to do all the steps you mentioned, you can sit relax and wait for the end result. HHAHAHHA :-)
Use imagick library to resize; it's good.

dynamic image resize using php

I have an image which i am going to be using as a background image and will be pulling some other images from the database that i want to show within this image. So if i am pulling only 1 image, i want the bottom part of the background image to close after the first image, if there are multiple images then i want it close after those images are shown. The problem with not using separate images is that the borders of the images have a design format and i cannot show them separately.
Take a look at this image . The design format of the right and left borders are more complicated than that to just crop them and use them. Any suggestions if there is any dynamic image resizing thing?
Yes there is. Look at the imageXXXX functions; the ones you are particularly interested in are imagecreate, imagecreatetruecolor, imagecreatefrompng, imagecopyresampled, imagecopyresized, and imagepng (assuming you're dealing with PNG images - there's similar load / save functions for jpeg, gif, and a few other formats).
You should try using the GD extension for PHP, especially have a look at imagecopyresized(). This allows you to do some basic image conversion and manipulation very easily.
A basic example that takes two GET parameters, resizes our myImage.jpg image and outputs it as a PNG image:
<?php
// width and height
$w = $_GET['w'];
$h = $_GET['h'];
// load image
$image = imagecreatefromjpeg('myImage.jpg');
// create a new image resource for storing the resized image
$resized = imagecreatetruecolor($w, $h);
// copy the image
imagecopyresized($resized, $image, 0, 0, 0, 0, $w, $h, imagesx($image), imagesy($image));
// output the image as PNG
header('Content-type: image/png');
imagepng($resized);
Have you tried PHPThumb? I used this class often and its pretty clean and lightweight. I used it here.

Categories