Search code examples
phpmysqlcropjcrop

Approach for storing image crops


We have a custom built CMS which allows for image uploads. In the CMS we have implemented jCrop. When cropping an image (with GD in PHP), we are storing the original image name and crop image name in the database (MySQL), aswel as the original image and crop image on the server.

When we need an alternate crop, we use PHP to create another crop of the cropped image (and save it to the server). Because such an image has now been processed by GD twice, the result often looks bad.

A possible use case: in the CMS we manage persons. Each person can have an image. Since persons are usually shown in portrait mode, we let the user crop in portrait. On the website this works out fine, but on the mobile website, we actually need a square image. Hence we need two crops.

Lately we've been wondering how we could improve our crop workflow. Would an approach of only storing crop coordinates in the database work on the long term? What is a common approach of dealing with crops?

Thanks in advance!


Solution

  • I would use this approach:

    • Upload an image. Assign it an unique ID (i.e. an MD5 hash of the name).
    • Let the user crop it, store only the coordinates and image name in the db
    • Store the cropped image, give it a filename that is made for example out of the original file name plus the coordinates of the crop.

    In this way you will be able to retrieve the cropped image only by knowing it's original name and the coordinates of the crop. In addition an exact duplicate of any crop would not be stored.

    Example:

    md5('image.jpg' . $crop->x0 . $crop->x1 . $crop->y0 . $crop->y1);