PHPackages                             marrouchi/upload-crop-image-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [File &amp; Storage](/categories/file-storage)
4. /
5. marrouchi/upload-crop-image-bundle

ActiveSymfony-bundle[File &amp; Storage](/categories/file-storage)

marrouchi/upload-crop-image-bundle
==================================

Basic server side cropping behavior for Symfony2

0.1.1(10y ago)111.1k5[1 issues](https://github.com/anis-marrouchi/UploadCropImageBundle/issues)MITCSSPHP &gt;=5.3.9

Since Jun 24Pushed 10y ago3 watchersCompare

[ Source](https://github.com/anis-marrouchi/UploadCropImageBundle)[ Packagist](https://packagist.org/packages/marrouchi/upload-crop-image-bundle)[ Docs](https://github.com/anis-marrouchi/UploadCropImageBundle)[ RSS](/packages/marrouchi-upload-crop-image-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (3)Versions (3)Used By (0)

UploadCropImageBundle
=====================

[](#uploadcropimagebundle)

Upload and crop an image for Symfony2 This bundle helps you add a custom file form field. You can single upload and crop an image. The bundle is based on the JCrop JQuery library. Your contribution is welcome.

Requirements:
=============

[](#requirements)

- PHP GD2 extension
- JQuery
- friendsofsymfony/jsrouting-bundle

Demo:
=====

[](#demo)

[![Animated GIF demo](https://raw.githubusercontent.com/anis-marrouchi/UploadCropImageBundle/master/Resources/doc/images/crop.gif)](https://raw.githubusercontent.com/anis-marrouchi/UploadCropImageBundle/master/Resources/doc/images/crop.gif)

Installation
============

[](#installation)

---

1. Add this bundle to your project in composer.json:

    ```
    {
        "require": {
            "marrouchi/upload-crop-image-bundle": "dev-master",
        }
    }
    ```
2. Register UploadCropImageBundle in your app/AppKernel.php:

    ```
    // app/AppKernel.php
    public function registerBundles()
    {
        return array(
            // ...
            new FOS\JsRoutingBundle\FOSJsRoutingBundle(),
            new Marrouchi\UploadCropImageBundle\UploadCropImageBundle(),
            // ...
        );
    }
    ```

And don't forget the JsRoutingBundle.

3. Add Media entity, run schema update to generate table, and install assets (Composer should install asset post the installation but just in case)

    ```
    namespace YourNamespace\YourBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;

    /**
     * Description: Media
     * @todo adjust to your need if you want to handle uploads by lifecyclecallback
     * @ORM\Entity
     * @ORM\Table()
     * //@ORM\HasLifecycleCallbacks name;
        }

        public function setName($name) {
            $this->name = $name;

            return $this;
        }

        /**
         * @ORM\Column(type="string", length=255, nullable=true)
         */
        protected $path;

        public function setPath($path) {
            $this->path = $path;

            return $this;
        }

        public function getPath() {
            return $this->path;
        }

        /**
         * @ORM\Column(name="created",type="date")
         */
        protected $created;

        /**
         * @var File
         *
         * @Assert\File(
         *     maxSize = "1M",
         *     mimeTypes = {"image/jpeg"},
         *     maxSizeMessage = "The maxmimum allowed file size is 5MB.",
         *     mimeTypesMessage = "Only the filetypes image are allowed."
         * )
         */
        protected $file;

        public function __construct() {
            $this->created = new \Datetime();
        }

        public function getUploadRootDir() {
            // absolute path to your directory where images must be saved
            return __DIR__ . '/../../../../web/' . $this->getUploadDir();
        }

        public function getUploadDir() {
            return 'uploads/';
        }

        public function getAbsolutePath() {
            return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->id . '.' . $this->path;
        }

        public function getWebPath() {
            return null === $this->name ? null : '/' . $this->getUploadDir() . '/' . $this->name;
        }

        /**
         * @ORM\PrePersist()
         * @ORM\PreUpdate()
         */
        public function preUpload() {
            if (null !== $this->file) {
                // faites ce que vous voulez pour gÃ©nÃ©rer un nom unique
                $filename = sha1(uniqid(mt_rand(), true));
                $this->name = $filename;
                $this->path = $filename . '.' . $this->file->guessExtension();
            }
        }

        /**
         * @ORM\PostPersist()
         * @ORM\PostUpdate()
         */
        public function upload() {
            if (null === $this->file) {
                return;
            }

            // s'il y a une erreur lors du dÃ©placement du fichier, une exception
            // va automatiquement Ãªtre lancÃ©e par la mÃ©thode move(). Cela va empÃªcher
            // proprement l'entitÃ© d'Ãªtre persistÃ©e dans la base de donnÃ©es si
            // erreur il y a
            $this->file->move($this->getUploadRootDir(), $this->path);

            unset($this->file);
        }

        /**
         * @ORM\PreRemove()
         */
        public function storeFilenameForRemove() {
            $this->filenameForRemove = $this->getAbsolutePath();
        }

        /**
         * @ORM\PostRemove()
         */
        public function removeUpload() {
            if ($this->filenameForRemove) {
                unlink($this->filenameForRemove);
            }
        }

        /**
         * Get id.
         *
         * @return int
         */
        public function getId() {
            return $this->id;
        }

        /**
         * Set created.
         *
         * @param \DateTime $created
         *
         * @return Media
         */
        public function setCreated($created) {
            $this->created = $created;

            return $this;
        }

        /**
         * Get created.
         *
         * @return \DateTime
         */
        public function getCreated() {
            return $this->created;
        }

        /* Set file
         *
         * @param $file
         * @return Media
         */

        public function setFile($file) {
            $this->file = $file;

            return $this;
        }

        /**
         * Get file.
         *
         * @return $file
         */
        public function getFile() {
            return $this->file;
        }

    }
    ```

    ```
    php app/console doctrine:schema:update --force
    ```

    ```
    php app/console asset:install
    ```
4. Include the route to your routing.yml and the config to your config.yml:

    ```
    upload_crop_image:
        resource: "@UploadCropImageBundle/Resources/config/routing.yml"
        prefix:   /
    ```

If you did not install the JSroutingBundle include them.

```
``` yml
# app/config/routing.yml
fos_js_routing:
	resource: "@UploadCropImageBundle/Resources/config/routing/routing.xml"
```

``` yml
upload_crop_image:
    media_entity: YourNamespace\YourBundle\Entity\Media
```

```

5. include the style and the javascript in your templates. The demo include is for demo purposes.

    ```

        …

        {% include 'UploadCropImageBundle:Commun:demo.includes.html.twig' %}
        {% include 'UploadCropImageBundle:Commun:crop.includes.html.twig' %}

    ```
6. Include the javascript before the closing body tag

    ```

        …
    {% include "UploadCropImageBundle:Commun:script.html.twig" %}

    ```
7. Add the following to your Media/Image/Photo form type buildForm method

    ```
     ``` php
     public function buildForm(FormBuilderInterface $builder, array $options) {
             $builder
                     …
                     ->add('file', 'file')
                     ->add('dimensions', 'crop_image', array('mapped' => false, 'label' => false))
                     …
             ;
         }
     ```

    ```
8. Now in your view, where you are rendering the form, include the following

    ```
    ``` html
    …

    …
    ```

    ```
9. Now add the form tag the coordinate checker and render your file field like so. You can pass the route for upload thru the html data attributes. supported data attributes are data-route, the route you will handle the upload and the data-id attributes used to handle any extra route id parameter.

    ```
    …

    …
    {{ form_widget(form.file, {'id':'file','data-route':'media_json_upload'})}}
    ```

If you are rendering the form fields individually, you will need to include the following to your form

```
``` twig
…
{{ form_widget(form.dimensions) }}
…
```

```

And that's it, let me know if you are facing some problem and let me know ways i can improve the bundle. Enjoy! ;)

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

2

Last Release

3976d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/99765b17bcdd6f772e2d82b7e9930cb2f9f5aa0cd181d84ba6d002612b45ff40?d=identicon)[marrouchi](/maintainers/marrouchi)

---

Top Contributors

[![anis-marrouchi](https://avatars.githubusercontent.com/u/3036133?v=4)](https://github.com/anis-marrouchi "anis-marrouchi (33 commits)")

---

Tags

imageuploadcrop

### Embed Badge

![Health badge](/badges/marrouchi-upload-crop-image-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/marrouchi-upload-crop-image-bundle/health.svg)](https://phpackages.com/packages/marrouchi-upload-crop-image-bundle)
```

###  Alternatives

[comur/image-bundle

A bundle providing fields for image upload with jquery upload and image cropping with jcrop for symfony2

104119.4k](/packages/comur-image-bundle)[contributte/image-storage

Image storage for Nette framework

28749.3k1](/packages/contributte-image-storage)[noam148/yii2-image-manager

A Yii2 module/widget for upload and cropping images

12914.8k](/packages/noam148-yii2-image-manager)[ublaboo/image-storage

Image storage for Nette framework

2913.0k](/packages/ublaboo-image-storage)[karpoff/yii2-crop-image-upload

Yii 2 Crop image upload widget

1818.5k](/packages/karpoff-yii2-crop-image-upload)[sadovojav/yii2-image-cutter

Yii2 crop image widget

108.6k](/packages/sadovojav-yii2-image-cutter)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
