PHP Image manipulation with rotation and crop - php

I have a problem with image manipulation in php. As they say, a picture paints a thousand words so below is an image to assist me in explaining my situation.
I have a canvas (the picture of a car) and a container (the red rectangle) and the image above is my initial setup. Here are the details that I know about my initial setup:
Dimension of the canvas (width & height)
Dimension of the container (width & height)
Position of the container relative to the top left of the canvas (x, y)
Next I apply a rotation on the canvas at a certain angle counter-clockwise. Assuming the centre of the rotation is the centre of the canvas itself.
As of this step, I know 2 additional details:
The angle of the rotation
The direction of the rotation (counter-clockwise)
Things to take note of:
The container itself didn't rotate, just the canvas.
The dimension of the canvas may have changed. In this case, both the width and height of the canvas have increased.
Details that I DO NOT know anymore AFTER the rotation:
Dimension of the canvas
Position of the container relative to the top left of the canvas
Then, the container is used to crop the canvas at its current position. The image below is the result I'm trying to achieve using php.
I have never done any image manipulation in php before. Code examples are greatly appreciated.

I found the answer here
Crop and rotate images with JS and PHP
I didn't know that we have to manually get the dimension of the canvas after the rotation and recalculate the relative position of the container based on the new canvas dimension.

Andy Croxall wrote a really good overview of image manipulation with PHP on Smashing Magazine:
http://coding.smashingmagazine.com/2011/04/05/image-manipulation-with-jquery-and-php-gd/
But I wouldn't bother reinventing the wheel here - Cloudinary pretty much did all the work for you. They even have a free 500MB plan you can use to test it out and compare results. Here's an overview of their image manipulation capabilities:
http://cloudinary.com/features#image_manipulation
Good luck !
Ohad

Related

Facebook style Cover photo upload, reposition, crop and save using php and jquery in bootstrap3

I am a newbie to web development and am trying to build my first website. I use PHP, Jquery and Bootstrap3 for my development. I want to add a Faceebook like cover photo upload and reposition feature on my site and it's been bit of a head ache. I have implemented all the features successfully by taking help from tutorials available here and here, but both of them are not perfect.
In both the tutorials, everything works fine until the final stage where you save the new repositoned image.
In the first approach, upon save, the new position of the image, the height and width of the container div are taken as inputs and a new image is generated using imagecreatetruecolor($width, $height);. The original image is saved separately and used if you want to reposition again.
In the second approach, simply the new position of the image is saved in the db and the same is set as "margin-top" for the (so called) repositioned image on page load.
Problems
The first approach is actually doing a good job by saving the images separately. However, the issue here is, the dimensions of the new image are set as per the dimensions of the container div. Since my container div is responsive, the height and width vary on screen size, and so does the actual size of the image. This is a disaster because if you crop the image on a mobile screen, the width is set to 200px and the same image is loaded on large screens, where the container width is close to 600px. It creates an empty whitespace.
The second approach is not doing anything but position the same image using css. The original image of big size is unnecessarily loaded every time.
I have implemented the first approach and made a lot of changes to fit my needs.
The problem is better illustrated in this .gif image on Imagur. Also please refer my other Stack Overflow question Scale down images effectively without losing aspect ratio or quality in php for more detailed explanation.
I have been struggling for more than a month now to figure out how to effectively crop the new image and save it so that it is consistent on all screen sizes.
I hope some expert can give me a solution for this so that I can launch my dream website without further delay.
Thank you
You don't have to generate a new image if the size of the screen changes. You can simply use percentages to maintain the original aspect ratio of the image.
You simply need to set the container to whatever width you want, then don't set the height, and set a child img to fill the entire width of the container. The height of the image will automatically scale to maintain the original aspect ratio:
div.aspect
{
width: 75%;
}
div.aspect img
{
width: 100%;
}
JSFiddle

PHP image resize ratio issue

Php thumb resize image based on provided width and height, I am working on profile image which is: 130x130
While users are uploading image of long heights(rectangle) which leads to strecthed image in its width and when uploading long width image(rectangle) then strecthed, I hope you understand what I mean. Because when anyone uses a large square image it resize to correct 130x130 but longer width and height get strecthed.
I am thinking of having a good suggestion or idea to work around such images, either crop them from top to make them perfect square first.
Thanks,
Najm.
Usually you will take the longer side, scale it up and scale the shorter side by the same percentage. One such snippet is here. You can also prefill the canvas with a smooth background that fits with your overall design.

php resize thumbnail to fixed dimensions - no crop

I want to resize an image to a fixed size of 400x300.
I do not want to zoom crop it, I simply want the image constrained to either the width 400 or height 300 (depending on orientation), the image centered, and the rest of the image filled with black.
Does anyone know of a library/code that does this? (for GD)
Thanks,
Wesley
GD or ImageMagick can easily do this for you.
Create a new image with a black background of the desired height, then copy from the original, and place in the new.
Perhaps another answer will come along with the full code, but this will get you started. If not, I will post code for you later.

How to detect an 'image area' percentage inside an image?

Mhh, kinda hard to explain with my poor english ;)
So, lets say I have an image, doesnt matter what kind of (gif, jpg, png) with 200x200 pixel size (total area 40000 pixels)
This image have a background, that can be trasparent, or every color (but i know the background-color in advance).
Lets say that in the middle of this image, there is a picture (for keep the example simple lets suppose is a square drawn), of 100x100 pixels (total area 10000 pixels).
I need to know the area percentage that the small square fill inside the image.
So, in i know the full image size and the background-color, there is a way in php/python to scan the image and retrieve that (in short, counting the pixel that are different from the given background)?
In the above example, the result should be 25%
EDIT: this are two image as example (gimped oin the way ;):
I need to know the percentage of the green pepper in the whole image (that is 400x400)
from PIL import Image
image = Image.open("pepper.png")
bg = image.getpixel((0,0))
width, height = image.size
bg_count = next(n for n,c in image.getcolors(width*height) if c==bg)
img_count = width*height - bg_count
img_percent = img_count*100.0/width/height
gives 7.361875 for both images
I am assuming the surrounding area has only one colour and the object in the image can have any shape (so you need to find out its coordinates first, right?)
If you can use ImageMagick, it's easy.
Store size of image (40000 Pixels)
Send image to ImageMagick and trim the surrounding area using -trim (description here)
Compare size of resulting image (10000 Pixels) with that of original image
If you can't use ImageMagick, you will have to use GD to crop the surrounding area away. A rough description is in the answer to this question. I'm pretty sure this has been implemented in PHP already, though.
Using Python and PIL (Python Imaging Library) you could try the following (untested - credit goes to the original thread here):
from PIL import ImageChops
def trim(im, border):
bg = Image.new(im.mode, im.size, border)
diff = ImageChops.difference(im, bg)
bbox = diff.getbbox()
if bbox:
return im.crop(bbox)
else:
# found no content
raise ValueError("cannot trim; image was empty")
And then do your calculations based on width * height (before and after the trim).
It depends a bit on your accuracy requirements and on the presence of the background color in the image. Consider this annoying test case:
Make a 400 pt large "G".
Make the text white. Hit "Shadow" or "Outline" so it surrounded by black.
Put it on a white background.
Pick your effort:
You can get a bounding box, which heavily overestimates the size of the 'G' because
of the large blank space inside.
You can count the white pixels, which heavily underestimates the size of the 'G' because of the many white pixels inside the outline.
You can pick a color not in the image, like blue, and run a recursive painter's algorithm from the top left corner. Then you can accurately count the blue pixels.
There are faster methods, which are more complicated.
You can usually use PIL (Python Imaging Library) http://www.pythonware.com/products/pil/ to access raw image data from the file formats.

PHP - Mask polygon over image

Hi Everyone (this is my first post),
I am trying to figure a way of cropping a polygon out of an image. I have been reading other similar code. It seems that most code is based around the following process:
Resize the image to fit the width and height of the polygon shape,
Create a blank image of an unusual colour the same size,
Overlay transparent pixels in the shape of the polygon,
Overlay that on to the resized image
Set the unusual colour to be transparent...
My problem is I do not want the code to be reliant on the unusual colour not being in the original image. Does anyone have a better method or some code which I can use to check if the unusual colour is in the image.
On a side note once I have cropped them I am looking to add a border only around the top and the left sides of the shape and three pixels in the corners to achieve a rounded corner effect... if anyone has any ideas about that then please also post.
If you draw the polygon in black-white (and brey values between) on a different image (called mask), you can use applyMask of the WideImage library.
See:
- http://wideimage.sourceforge.net/
- http://wideimage.sourceforge.net/wp-content/current/demo/index.php?demo=applyMask&output=preset%20for%20demo&colors=255&dither=&match_palette=
an alternative way would be to cut the big image in 4 parts ...
a top part,
left side and right side that are the parts on the left and right of the image afte the mask
and bottom part
and recompose them.
But that would require a bit of code and calculations.

Categories