有没有办法上传图像(JPEG)来检查DPI?

时间:2013-01-16 12:29:24

标签: php image-processing file-upload symfony1 symfony-1.4

上传图片(JPEG)以检查DPI是否有办法?

我想将它整合到一个表单中,以便作为验证器。

1 个答案:

答案 0 :(得分:3)

您必须使用Imagick(或Gmagick)打开图像,然后拨打getImageResolution

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

结果:

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

修改

要集成到symfony中,您可以使用自定义验证器。您扩展了默认值以验证文件并添加DPI限制。

将此项创建为/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;
  }
}

然后,在表单中,将此验证程序用于您的文件:

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