我正在使用 foresight.js 为视网膜设备加载高分辨率图像。Foresight 尝试用 2x 像素密度图像替换低分辨率图像。由于 foresight 试图在页面呈现之前替换低分辨率图像,因此我无法在模板中使用 GD 图像大小调整方法来调整大小的图像。因此,我允许 SS 3.1 cms 用户上传一张大图像并让系统在上传后重新调整它的大小 - 在 assets 文件夹中留下 1x 和 2x 图像。
我的问题是,如果 cms 用户没有上传足够大的图像,我该如何设置自定义验证错误消息?
这是在上传时调整图像大小的代码。
class ResampledImage extends Image {
static $default_lores_x = 250;
static $default_lores_y = 250;
static $default_hires_x = 500;
static $default_hires_y = 500;
static $default_assets_dir = 'Uploads';
static $hires_flag = '2x';
function getLoResX() {
return ( static::$lores_x ) ? static::$lores_x : self::$default_lores_x;
}
function getLoResY() {
return ( static::$lores_y ) ? static::$lores_y : self::$default_lores_y;
}
function getHiResX() {
return ( static::$hires_x ) ? static::$hires_x : self::$default_hires_x;
}
function getHiResY() {
return ( static::$hires_y ) ? static::$hires_y : self::$default_hires_y;
}
function getAssetsDir() {
return ( static::$assets_dir ) ? static::$assets_dir : self::$default_assets_dir;
}
function onAfterUpload() {
$this->createResampledImages();
}
function onAfterWrite() {
$this->createResampledImages();
}
function createResampledImages() {
$extension = strtolower($this->getExtension());
if( $this->getHeight() >= $this->getHiResX() || $this->getWidth() >= $this->getHiResY() ) {
$original = $this->getFullPath();
$resampled = $original. '.tmp.'. $extension;
$orig_title = $this->getTitle();
$path_to_hires = Director::baseFolder() . '/' . ASSETS_DIR . '/' . $this->getAssetsDir();
$hires = $path_to_hires . '/' . $orig_title . self::$hires_flag . '.' . $extension;
$gd_lg = new GD($original);
$gd_sm = new GD($original);
if ( $gd_lg->hasImageResource() ) {
$gd_lg = $gd_lg->resizeRatio($this->getHiResX(), $this->getHiResY());
if ( $gd_lg )
$gd_lg->writeTo($hires);
}
if($gd_sm->hasImageResource()) {
$gd_sm = $gd_sm->resizeRatio($this->getLoResX(), $this->getLoResY());
if($gd_sm) {
$gd_sm->writeTo($resampled);
unlink($original);
rename($resampled, $original);
}
}
}
}
查看 UploadField::setFileEditValidator() 似乎我可以在扩展的 Image 类上指定一个方法以用作验证器,以便我可以检查 $this->getWidth() 和 $this->getHeight() 并返回一个如果它们不够大,则会出错。
这可能吗?
我尝试将以下方法添加到 ResampledImage,但这不成功:
function MyValidator() {
$valid = true;
if ( $this->getHeight() < $this->getHiResX() || $this->getWidth() < $this->getHiResY() ) {
$this->validationError("Thumbnail",'Please upload a larger image');
$valid = false;
}
return $valid;
}