phpbb 3.2 Автоматическое изменение размеров аватаров при загрузке -- приведение к нужному разрешению (сжатие, "образка")

Изменения в коде phpbb

Делаем следующее:

  1. Открываем файл
     includes/functions_posting.php

    переходим к определению функции

     create_thumbnail() 

    И полностью заменяем её следующим кодом:

    /**
    * Create Thumbnail
    *
    * Modified by Dion Designs to support resizing avatars
    */
    function create_thumbnail($source, $destination, $mimetype, $new_width = 0, $new_height = 0) {
    	global $config;
    
    	if ($new_width) {
    		$destination = $source;
    	}
    	else {
    		$min_filesize = (int) $config['img_min_thumb_filesize'];
    		$img_filesize = (file_exists($source)) ? @filesize($source) : false;
    
    		if (!$img_filesize || $img_filesize <= $min_filesize) {
    			return false;
    		}
    	}
    
    	$dimension = @getimagesize($source);
    
    	if ($dimension === false) {
    		return false;
    	}
    	list($width, $height, $type, ) = $dimension;
    
    	if (empty($width) || empty($height)) {
    		return false;
    	}
    
    	if (!$new_width) {
    		list($new_width, $new_height) = get_img_size_format($width, $height);
    	}
    	else if ($height > $new_height || $width > $new_width) {
    		$h_ratio = $new_height / $height;
    		$w_ratio = $new_width / $width;
    		$scale_factor = ($h_ratio < $w_ratio) ? $h_ratio : $w_ratio;
    		$new_width = ($h_ratio < $w_ratio) ? round($width * $scale_factor) : $new_width;
    		$new_height = ($w_ratio < $h_ratio) ? round($height * $scale_factor) : $new_height;
    	}
    	else {
    		return false;
    	}
    
    	// Do not create a thumbnail if the resulting width/height is bigger than the original one
    	if ($new_width >= $width && $new_height >= $height) {
    		return false;
    	}
    
    	$used_imagick = false;
    
    	// Only use imagemagick if defined and the passthru function not disabled
    	if ($config['img_imagick'] && function_exists('passthru')) {
    		if (substr($config['img_imagick'], -1) !== '/')	{
    			$config['img_imagick'] .= '/';
    		}
    
    		@passthru(escapeshellcmd($config['img_imagick']) . 'convert' . ((defined('PHP_OS') && preg_match('#^win#i', PHP_OS)) ? '.exe' : '') . ' -quality 85 -geometry ' . $new_width . 'x' . $new_height . ' "' . str_replace('\\', '/', $source) . '" "' . str_replace('\\', '/', $destination) . '"');
    
    		if (file_exists($destination)) {
    			$used_imagick = true;
    		}
    	}
    
    	if (!$used_imagick) {
    		$type = get_supported_image_types($type);
    
    		if ($type['gd']) {
    			// If the type is not supported, we are not able to create a thumbnail
    			if ($type['format'] === false) {
    				return false;
    			}
    
    			switch ($type['format']) {
    				case IMG_GIF:
    					$image = @imagecreatefromgif($source);
    				break;
    
    				case IMG_JPG:
    					@ini_set('gd.jpeg_ignore_warning', 1);
    					$image = @imagecreatefromjpeg($source);
    				break;
    
    				case IMG_PNG:
    					$image = @imagecreatefrompng($source);
    				break;
    
    				case IMG_WBMP:
    					$image = @imagecreatefromwbmp($source);
    				break;
    			}
    
    			if (empty($image)) {
    				return false;
    			}
    
    			if ($type['version'] == 1) {
    				$new_image = imagecreate($new_width, $new_height);
    
    				if ($new_image === false) {
    					return false;
    				}
    
    				imagecopyresized($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    			}
    			else {
    				$new_image = imagecreatetruecolor($new_width, $new_height);
    
    				if ($new_image === false) {
    					return false;
    				}
    
    				// Preserve alpha transparency (png for example)
    				@imagealphablending($new_image, false);
    				@imagesavealpha($new_image, true);
    
    				imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    			}
    
    			// If we are in safe mode create the destination file prior to using the gd functions to circumvent a PHP bug
    			if (@ini_get('safe_mode') || @strtolower(ini_get('safe_mode')) == 'on') {
    				@touch($destination);
    			}
    
    			switch ($type['format']) {
    				case IMG_GIF:
    					imagegif($new_image, $destination);
    				break;
    
    				case IMG_JPG:
    					imagejpeg($new_image, $destination, 90);
    				break;
    
    				case IMG_PNG:
    					imagepng($new_image, $destination);
    				break;
    
    				case IMG_WBMP:
    					imagewbmp($new_image, $destination);
    				break;
    			}
    
    			imagedestroy($new_image);
    		}
    		else {
    			return false;
    		}
    	}
    
    	if (!file_exists($destination)) {
    		return false;
    	}
    
    	if (!$new_width) {
    		global $phpbb_filesystem;
    
    		try
    		{
    			$phpbb_filesystem->phpbb_chmod($destination, CHMOD_READ | CHMOD_WRITE);
    		}
    		catch (\phpbb\filesystem\exception\filesystem_exception $e)
    		{
    			// Do nothing
    		}
    	}
    	return array($new_width, $new_height);
    }
    

    И сохраняем файл.

  2. Далее открываем файл:
    phpbb/avatar/driver/upload.php

    Находим строчку:

    $file->clean_filename('avatar', $prefix, $row['id']);

    И заменяем её на:

    //	MODIFICATION BY DION DESIGNS
    		$upload->set_allowed_dimensions($this->config['avatar_min_width'], $this->config['avatar_min_height'], 65535, 65535);
    //	END MODIFICATION
    
    		$file->clean_filename('avatar', $prefix, $row['id']);
    
    //	MODIFICATION BY DION DESIGNS
    		// resize uploaded avatar
    		include_once($this->phpbb_root_path . 'includes/functions_posting.' . $this->php_ext);
    		@ini_set('memory_limit','128M');
    		$result = create_thumbnail($file->get('filename'), '', '', $this->config['avatar_max_width'], $this->config['avatar_max_height']);
    		$width = $file->get('width');
    		$height= $file->get('height');
    		if ($result) {
    			list($width, $height) = $result;
    		}
    //	END MODIFICATION
    
  3. И в той же функции (в том же файле) ниже находим место возврата значения:
    return array(
    			'avatar' => $row['id'] . '_' . time() . '.' . $file->get('extension'),
    			'avatar_width' => $file->get('width'),
    			'avatar_height' => $file->get('height'),
    		);
    

    И заменяем его на:

    		return array(
    			'avatar' => $row['id'] . '_' . time() . '.' . $file->get('extension'),
    			'avatar_width' => $width,
    			'avatar_height' => $height,
    		);
    
  4. Сохраняем файл. Теперь аватары будут подгоняться к максимальный ширине/высоте (пропорционально) -- даже если до этого они были, шириномй например в 65000 пикселей

Источник: Идея этих правок полность принадлежит этому товарищу: https://forum.dion-designs.com//p14564/#... За что му огромное спасибо.

Настройки максимального размера загружаемого файла

Предыдущий код, хороши всем, что касается разрешения изображения, но есть одна проблема -- его размер (вес).

Если вы хотите загружать файл размером более 2 мегабайт -- нужно править php.ini (просто выставить настройки не достаточно) и выставить ,например:

upload_max_filesize = 15M

-- этого должно хватить для большинства цифровых фотоаппаратов.

Это же в принципе можно сделать и через .htaccess если вы (или ваш хостинг-провайдер) используете -веб-сервер Апач -- не забудьте увеличить до этого же значения и размер пост-запроса:

php_value upload_max_filesize 15M
php_value post_max_size 15M