【问题标题】:Is there a way when uploading images (JPEG) to check the DPI?上传图像 (JPEG) 时有没有办法检查 DPI?
【发布时间】:2013-01-16 12:29:23
【问题描述】:

上传图片 (JPEG) 时有没有办法检查 DPI?

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

【问题讨论】:

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


【解决方案1】:

您必须使用 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
));

【讨论】:

  • 这可以和 sfWidgetFormInputFileEditable 一起完成吗?
  • 您想何时检查 DPI?在保存图像之前?
  • 理想情况下是的。我正在处理的应用程序要求所有上传的图像为 300DPI
  • 太棒了!!我会试试看1
  • 我试过这个,但它会抛出一个错误:Fatal error: Class 'Gd not found'
猜你喜欢
  • 2021-07-10
  • 2013-07-09
  • 2010-10-24
  • 2020-04-01
  • 2012-02-14
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多