marrouchi/upload-crop-image-bundle

Symfony2的基本服务器端裁剪行为

安装次数: 1,125

依赖者: 0

建议者: 0

安全: 0

星标: 11

关注者: 5

分支: 5

开放问题: 1

语言:CSS

类型:symfony-bundle

0.1.1 2015-06-30 01:29 UTC

This package is not auto-updated.

Last update: 2024-09-24 03:28:42 UTC


README

为Symfony2上传并裁剪图片 此扩展帮助您添加自定义文件表单字段。您可以单独上传和裁剪图片。该扩展基于JCrop JQuery库。欢迎您的贡献。

要求

  • PHP GD2扩展
  • JQuery
  • friendsofsymfony/jsrouting-bundle

演示

Animated GIF demo

安装

  1. 将此扩展添加到您的项目的composer.json中

    {
        "require": {
            "marrouchi/upload-crop-image-bundle": "dev-master",
        }
    }
    
  2. 在您的app/AppKernel.php中注册UploadCropImageBundle

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

别忘了JsRoutingBundle。

  1. 添加媒体实体,运行模式更新以生成表,并安装资产(Composer应在安装后安装资产,但以防万一)

    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 <-
     */
    class Media {
    
        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;
    
        /**
         * @ORM\Column(type="string", length=255)
         */
        protected $name;
    
        public function getName() {
            return $this->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
  2. 在您的routing.yml中包含路由,在您的config.yml中包含配置

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

如果您没有安装JSroutingBundle,请包括它们。

``` 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
```
  1. 在您的模板中包含样式和javascript。演示包含仅用于演示目的。

        <head>
        …
        <script src="{{asset("bundles/uploadcropimage/js/jquery.min.js") }}"></script>
        <script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
        <script src="{{ path('fos_js_routing_js', {'callback': 'fos.Router.setData'}) }}"></script>
        {% include 'UploadCropImageBundle:Commun:demo.includes.html.twig' %}
        {% include 'UploadCropImageBundle:Commun:crop.includes.html.twig' %}
    </head>
  2. 在关闭body标签之前包含javascript

    <body>
        …
    {% include "UploadCropImageBundle:Commun:script.html.twig" %}
    </body>
  3. 将以下内容添加到Media/Image/Photo表单类型buildForm方法中

     ``` php
     public function buildForm(FormBuilderInterface $builder, array $options) {
             $builder
                     …
                     ->add('file', 'file')
                     ->add('dimensions', 'crop_image', array('mapped' => false, 'label' => false))
                     …
             ;
         }
     ```
    
  4. 现在在您的视图中,您渲染表单的地方,包括以下内容

    ``` html
    …
    <div id="jcrop-holder">
    <img src="holder.js/300x300?bg=#b8ebb8&fg=#ffffff" id="cropbox">
    </div>
    …
    ```
    
  5. 现在添加表单标签坐标检查器,并按如下方式渲染文件字段。您可以通过html数据属性传递上传路由。支持的数据属性是data-route,您将处理上传的路由,以及data-id属性,用于处理任何额外的路由id参数。

    …
    <form name="upload" action="{{ path('your_path') }}" {{ form_enctype(form) }} method="POST"  onsubmit="return checkCoords();">
    …
    {{ form_widget(form.file, {'id':'file','data-route':'media_json_upload'})}}

如果您单独渲染表单字段,您需要在您的表单中包含以下内容

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

就这样,如果遇到问题,请告诉我,并让我知道我可以如何改进此扩展。祝您享受! ;)