#php #image-processing #png #transparency #gd
#php #обработка изображений #png #прозрачность #б — г
Вопрос:
У меня есть система загрузки изображений PHP, которая позволяет пользователю загружать различные изображения (JPG, GIF, PNG). Каждое загружаемое изображение имеет значок (20×20), миниатюру (150×150) и открытку (500×500), сгенерированную для него — я называю эти «мета-изображения». Если размеры исходного изображения не квадратные, как у метаизображения, оно масштабируется до наилучшего соответствия и создается прозрачный холст нужного размера с наложенным на него метаизображением. Из-за этого прозрачного холста и для других целей все сгенерированные мета-изображения сами по себе являются PNG (независимо от формата исходного изображения).
Например, если пользователь загружает изображение JPG размером 800 на 600 пикселей, в файловой системе появляется следующее:
- Оригинал *.jpg размером 800 x 600
- Значок Meta *.png с копией исходного изображения размером 20 x 15, центрированной по горизонтали и вертикали на прозрачном холсте размером 20 x 20
- Мета thumbail *.png с копией исходного изображения размером 150 x 112, центрированной по горизонтали и вертикали на 150 x 150 прозрачном холсте
- Значок Meta *.png с копией исходного изображения размером 500 x 375, центрированной по горизонтали и вертикали на прозрачном холсте размером 500 x 500
Это отлично работает для файлов JPG и GIF — все цвета обрабатываются должным образом, размеры работают и т.д. и т.п. И т.п.
Однако, если я загружаю PNG, в котором есть какой-либо черный цвет (rgb (0,0,0), #000000), в результате 3 мета-изображения будут полностью черными, преобразованными в прозрачные. Все остальное в порядке — размеры и т.д. И помните, прозрачные GIF-файлы, похоже, работают нормально, даже если внутри есть черный цвет.
Может кто-нибудь, пожалуйста, объяснить мне, как я могу это исправить? Ниже приведен код, который я написал для этой системы (обратите внимание, что под ним определены 3 расширения абстрактного класса):
<?php
/*
* TODO: There is no reason for this class to be abstract except that I have not
* added any of the setters/getters/etc which would make it useful on its
* own. As is, an instantiation of this class would not accomplish
* anything so I have made it abstract to avoid instantiation. Three
* simple and usable extensions of this class exist below it in this file.
*/
abstract class ObjectImageRenderer
{
const WRITE_DIR = SITE_UPLOAD_LOCATION;
protected $iTargetWidth = 0;
protected $iTargetHeight = 0;
protected $iSourceWidth = 0;
protected $iSourceHeight = 0;
protected $iCalculatedWidth = 0;
protected $iCalculatedHeight = 0;
protected $sSourceLocation = '';
protected $sSourceExt = '';
protected $oSourceImage = null;
protected $sTargetLocation = '';
protected $sTargetNamePrefix = '';
protected $oTargetImage = null;
protected $oTransparentCanvas = null;
protected $bNeedsCanvas = false;
protected $bIsRendered = false;
public function __construct( $sSourceLocation )
{
if( ! is_string( $sSourceLocation ) || $sSourceLocation === '' ||
! is_file( $sSourceLocation ) || ! is_readable( $sSourceLocation )
)
{
throw new Exception( __CLASS__ . ' must be instantiated with valid path/filename of source image as first param.' );
}
$this->sSourceLocation = $sSourceLocation;
$this->resolveNames();
}
public static function factory( $sSourceLocation, $size )
{
switch( $size )
{
case 'icon':
return new ObjectIconRenderer( $sSourceLocation );
break;
case 'thumbnail':
return new ObjectThumbnailRenderer( $sSourceLocation );
break;
case 'postcard':
return new ObjectPostcardRenderer( $sSourceLocation );
break;
}
}
public static function batchRender( $Source )
{
if( is_string( $Source ) )
{
try
{
ObjectImageRenderer::factory( $Source, 'icon' )->render();
ObjectImageRenderer::factory( $Source, 'thumbnail' )->render();
ObjectImageRenderer::factory( $Source, 'postcard' )->render();
}
catch( Exception $exc )
{
LogProcessor::submit( 500, $exc->getMessage() );
}
}
else if( is_array( $Source ) amp;amp; count( $Source ) > 0 )
{
foreach( $Source as $sSourceLocation )
{
if( is_string( $sSourceLocation ) )
{
self::batchRender( $sSourceLocation );
}
}
}
}
/**
* loadImageGD - read image from filesystem into GD based image resource
*
* @access public
* @static
* @param STRING $sImageFilePath
* @param STRING $sSourceExt OPTIONAL
* @return RESOURCE
*/
public static function loadImageGD( $sImageFilePath, $sSourceExt = null )
{
$oSourceImage = null;
if( is_string( $sImageFilePath ) amp;amp; $sImageFilePath !== '' amp;amp;
is_file( $sImageFilePath ) amp;amp; is_readable( $sImageFilePath )
)
{
if( $sSourceExt === null )
{
$aPathInfo = pathinfo( $sImageFilePath );
$sSourceExt = strtolower( (string) $aPathInfo['extension'] );
}
switch( $sSourceExt )
{
case 'jpg':
case 'jpeg':
case 'pjpeg':
$oSourceImage = imagecreatefromjpeg( $sImageFilePath );
break;
case 'gif':
$oSourceImage = imagecreatefromgif( $sImageFilePath );
break;
case 'png':
case 'x-png':
$oSourceImage = imagecreatefrompng( $sImageFilePath );
break;
default:
break;
}
}
return $oSourceImage;
}
protected function resolveNames()
{
$aPathInfo = pathinfo( $this->sSourceLocation );
$this->sSourceExt = strtolower( (string) $aPathInfo['extension'] );
$this->sTargetLocation = self::WRITE_DIR . $this->sTargetNamePrefix . $aPathInfo['basename'] . '.png';
}
protected function readSourceFileInfo()
{
$this->oSourceImage = self::loadImageGD( $this->sSourceLocation, $this->sSourceExt );
if( ! is_resource( $this->oSourceImage ) )
{
throw new Exception( __METHOD__ . ': image read failed for ' . $this->sSourceLocation );
}
$this->iSourceWidth = imagesx( $this->oSourceImage );
$this->iSourceHeight = imagesy( $this->oSourceImage );
return $this;
}
protected function calculateNewDimensions()
{
if( $this->iSourceWidth === 0 || $this->iSourceHeight === 0 )
{
throw new Exception( __METHOD__ . ': source height or width is 0. Has ' . __CLASS__ . '::readSourceFileInfo() been called?' );
}
if( $this->iSourceWidth > $this->iTargetWidth || $this->iSourceHeight > $this->iTargetHeight )
{
$nDimensionRatio = ( $this->iSourceWidth / $this->iSourceHeight );
if( $nDimensionRatio > 1 )
{
$this->iCalculatedWidth = $this->iTargetWidth;
$this->iCalculatedHeight = (int) round( $this->iTargetWidth / $nDimensionRatio );
}
else
{
$this->iCalculatedWidth = (int) round( $this->iTargetHeight * $nDimensionRatio );
$this->iCalculatedHeight = $this->iTargetHeight;
}
}
else
{
$this->iCalculatedWidth = $this->iSourceWidth;
$this->iCalculatedHeight = $this->iSourceHeight;
}
if( $this->iCalculatedWidth < $this->iTargetWidth || $this->iCalculatedHeight < $this->iTargetHeight )
{
$this->bNeedsCanvas = true;
}
return $this;
}
protected function createTarget()
{
if( $this->iCalculatedWidth === 0 || $this->iCalculatedHeight === 0 )
{
throw new Exception( __METHOD__ . ': calculated height or width is 0. Has ' . __CLASS__ . '::calculateNewDimensions() been called?' );
}
$this->oTargetImage = imagecreatetruecolor( $this->iCalculatedWidth, $this->iCalculatedHeight );
$aTransparentTypes = Array( 'gif', 'png', 'x-png' );
if( in_array( $this->sSourceExt, $aTransparentTypes ) )
{
$oTransparentColor = imagecolorallocate( $this->oTargetImage, 0, 0, 0 );
imagecolortransparent( $this->oTargetImage, $oTransparentColor);
imagealphablending( $this->oTargetImage, false );
}
return $this;
}
protected function fitToMaxDimensions()
{
$iTargetX = (int) round( ( $this->iTargetWidth - $this->iCalculatedWidth ) / 2 );
$iTargetY = (int) round( ( $this->iTargetHeight - $this->iCalculatedHeight ) / 2 );
$this->oTransparentCanvas = imagecreatetruecolor( $this->iTargetWidth, $this->iTargetHeight );
imagealphablending( $this->oTransparentCanvas, false );
imagesavealpha( $this->oTransparentCanvas, true );
$oTransparentColor = imagecolorallocatealpha( $this->oTransparentCanvas, 0, 0, 0, 127 );
imagefill($this->oTransparentCanvas, 0, 0, $oTransparentColor );
$bReturnValue = imagecopyresampled( $this->oTransparentCanvas, $this->oTargetImage, $iTargetX, $iTargetY, 0, 0, $this->iCalculatedWidth, $this->iCalculatedHeight, $this->iCalculatedWidth, $this->iCalculatedHeight );
$this->oTargetImage = $this->oTransparentCanvas;
return $bReturnValue;
}
public function render()
{
/*
* TODO: If this base class is ever made instantiable, some re-working is
* needed such that the developer harnessing it can choose whether to
* write to the filesystem on render, he can ask for the
* image resources, determine whether cleanup needs to happen, etc.
*/
$this
->readSourceFileInfo()
->calculateNewDimensions()
->createTarget();
$this->bIsRendered = imagecopyresampled( $this->oTargetImage, $this->oSourceImage, 0, 0, 0, 0, $this->iCalculatedWidth, $this->iCalculatedHeight, $this->iSourceWidth, $this->iSourceHeight );
if( $this->bIsRendered amp;amp; $this->bNeedsCanvas )
{
$this->bIsRendered = $this->fitToMaxDimensions();
}
if( $this->bIsRendered )
{
imagepng( $this->oTargetImage, $this->sTargetLocation );
@chmod( $this->sTargetLocation, 0644 );
}
if( ! $this->bIsRendered )
{
throw new Exception( __METHOD__ . ': failed to copy image' );
}
$this->cleanUp();
}
public function cleanUp()
{
if( is_resource( $this->oSourceImage ) )
{
imagedestroy( $this->oSourceImage );
}
if( is_resource( $this->oTargetImage ) )
{
imagedestroy( $this->oTargetImage );
}
if( is_resource( $this->oTransparentCanvas ) )
{
imagedestroy( $this->oTransparentCanvas );
}
}
}
class ObjectIconRenderer extends ObjectImageRenderer
{
public function __construct( $sSourceLocation )
{
/* These Height/Width values are also coded in
* src/php/reference/display/IconUploadHandler.inc
* so if you edit them here, do it there too
*/
$this->iTargetWidth = 20;
$this->iTargetHeight = 20;
$this->sTargetNamePrefix = 'icon_';
parent::__construct( $sSourceLocation );
}
}
class ObjectThumbnailRenderer extends ObjectImageRenderer
{
public function __construct( $sSourceLocation )
{
/* These Height/Width values are also coded in
* src/php/reference/display/IconUploadHandler.inc
* so if you edit them here, do it there too
*/
$this->iTargetWidth = 150;
$this->iTargetHeight = 150;
$this->sTargetNamePrefix = 'thumbnail_';
parent::__construct( $sSourceLocation );
}
}
class ObjectPostcardRenderer extends ObjectImageRenderer
{
public function __construct( $sSourceLocation )
{
/* These Height/Width values are also coded in
* src/php/reference/display/IconUploadHandler.inc
* so if you edit them here, do it there too
*/
$this->iTargetWidth = 500;
$this->iTargetHeight = 500;
$this->sTargetNamePrefix = 'postcard_';
parent::__construct( $sSourceLocation );
}
}
Код, который я использую для его запуска, является:
<?php
ObjectImageRenderer::batchRender( $sSourceFile );
Основные проблемы, похоже, заключаются в createTarget()
и fitToMaxDimensions()
методах. В createTarget()
, если я закомментирую следующие строки:
$aTransparentTypes = Array( 'gif', 'png', 'x-png' );
if( in_array( $this->sSourceExt, $aTransparentTypes ) )
{
$oTransparentColor = imagecolorallocate( $this->oTargetImage, 0, 0, 0 );
imagecolortransparent( $this->oTargetImage, $oTransparentColor);
imagealphablending( $this->oTargetImage, false );
}
Я больше не теряю свой черный цвет, но вся существующая прозрачность становится черной.
Я предполагаю, что проблема в том, что я использую черный цвет в качестве канала прозрачности. Но как мне избежать использования цвета, который есть на изображении, в качестве канала прозрачности?
Спасибо всем, кто может помочь мне понять тайны прозрачности!
Джим
Комментарии:
1. Да, я, вероятно, переоценил предоставленные данные, но я назвал конкретные области, которые, по моему мнению, являются проблемой . По крайней мере, вам не нужно спрашивать у меня код… Тем не менее, это всего лишь файл в 345 строк, большая часть которого — комментарии и документы.
Ответ №1:
Вы явно указываете, что 0,0,0 является прозрачным:
$oTransparentColor = imagecolorallocatealpha( $this->oTransparentCanvas, 0, 0, 0, 127 );
Это будет применяться к ЛЮБОМУ пикселю в изображении, где триплет цвета равен 0,0,0 — другими словами, все черные, как вы находите.
Если вы хотите, чтобы исходные изображения проходили, вам следует преобразовать их в использование альфа-канала. Это был бы отдельный «слой» в изображении, который исключительно определяет прозрачность / непрозрачность для каждого пикселя. Это или отсканируйте изображения на предмет цвета, который не используется в оригинале, а затем укажите его в качестве нового значения прозрачности вместо значения по умолчанию 0,0,0.
Комментарии:
1. Ваш совет точен, и это то, о чем я читал раньше. Я просто не знал, как это сделать. Однако вы заставили меня переориентироваться в моем поиске в Google, и я нашел кое-что, что работает. Я оставляю фрагмент строк, о котором упоминал ранее из
createTarget()
, но добавляю проверку после них, чтобы увидеть, PNG ли это. Если это так, я также вызываюimagesavealpha( $this->oTargetImage, true );
2. Я грубо забыл упомянуть об этом в своем последнем комментарии — спасибо за ваше время и помощь. 🙂