Search code examples
phpimage-processingfile-uploadsymfony1symfony-1.4

Is there a way when uploading images (JPEG) to check the DPI?


Is there a way when uploading images (JPEG) to check the DPI?

I would like to integrate it into a form, so as a validator.


Solution

  • You have to open the image with Imagick (or Gmagick) and then call getImageResolution.

    $image = new Imagick($path_to_image);
    var_dump($image->getImageResolution());
    

    result:

    Array
    (
        [x]=>75
        [y]=>75
    )
    

    Edit:

    For an integration into symfony, you can use a custom validator for that. You extends the default one to validate a file and add the DPI restriction.

    Create this one into /lib/validator/myCustomValidatorFile .class.php:

    <?php
    
    class myCustomValidatorFile extends sfValidatorFile
    {
      protected function configure($options = array(), $messages = array())
      {
        parent::configure($options, $messages);
    
        $this->addOption('resolution_dpi');
        $this->addMessage('resolution_dpi', 'DPI resolution is wrong, you should use image with %resolution_dpi% DPI.');
      }
    
      protected function doClean($value)
      {
        $validated_file = parent::doClean($value);
    
        $image      = new Imagick($validated_file->getTempName());
        $resolution = $image->getImageResolution();
    
        if (empty($resolution))
        {
          throw new sfValidatorError($this, 'invalid');
        }
    
        if ((isset($resolution['x']) && $resolution['x'] < $this->getOption('resolution_dpi')) || (isset($resolution['y']) && $resolution['y'] < $this->getOption('resolution_dpi')))
        {
          throw new sfValidatorError($this, 'resolution_dpi', array('resolution_dpi' => $this->getOption('resolution_dpi')));
        }
    
        return $validated_file;
      }
    }
    

    Then, inside your form, use this validator for your file:

    $this->validatorSchema['file'] = new myCustomValidatorFile(array(
      'resolution_dpi' => 300,
      'mime_types'     => 'web_images',
      'path'           => sfConfig::get('sf_upload_dir'),
      'required'       => true
    ));