Skip to content
Advertisement

Crop Uploaded Image To 1:1 Ratio PHP

I have my own PHP function allowing users to update their profile image.

It all works fine, however, I am having a problem where users can upload any size image they want; i.e: 564 x 346.

I do not want this to happen. I would like the image that they select to upload to be cropped to a 1:1 ratio and centred; i.e: it goes from 564 x 346 to 346 x 346 and centres to the middle of the image.

None of the scripts that I have found seem to work for my site (at least the way I want them to).

This is the code I am currently using to update their avatar. It consists of checking if they have a correct file extension & if the image is less than 256kb in size:

JavaScript

This is the updateAvatar() function that I have made and is called on line 13:

JavaScript

However, this is not enough and does not allow my users profile page to work or look the way it should, I am going for something along the lines of how Google or Twitter do their avatar’s.

All help is appreciated. Cheers.

Advertisement

Answer

There is imagecrop() function in php:

JavaScript

I haven’t tried this code but I’m quite sure it’s right. Try it and tell me if it doesn’t work.

UPDATE: Then you can save the resource $image with imagejpeg() or imagepng() to save the images with the same extensions so you won’t have problems with the database:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement