操纵透明PNG会使图像中的所有rgb(0,0,0)变为透明。

| 我有一个PHP图像上传系统,该系统允许用户上传各种图像(JPG,GIF,PNG)。上传的每个图像都有一个图标(20x20),缩略图(150x150)和为其生成的明信片(500x500),我将其称为“元图像”。如果原始图像的尺寸不像元图像那样为正方形,则将其缩放为最佳尺寸,并以适当的尺寸生成透明画布,并在其上放置元图像。由于这种透明的画布绘制,并且出于其他目的,所有生成的元图像本身都是PNG(与原始图像格式无关)。 例如,如果用户上传800px x 600px的JPG图像,则以下内容将在文件系统中显示: 原始* .jpg(分辨率为800 x 600) 带有20 x 15原始图像副本的元图标* .png在20 x 20 tansparent画布上水平和垂直居中 带有150 x 112原始图像副本的元Thumbail * .png,在150 x 150 tansparent画布上水平和垂直居中 带有500 x 375原始图片副本的元图标* .png,在500 x 500 tansparent画布上水平和垂直居中 这非常适合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 ) && 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 ) && $sImageFilePath !== \'\' &&
        is_file( $sImageFilePath ) && 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 && $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 );
}
我不再失去黑色,但是所有现有的透明度都变成了黑色。 我认为问题是我使用黑色作为透明通道。但是如何避免使用图像中的颜色作为透明通道? 感谢任何可以帮助我了解透明度背后的奥秘的人! 吉姆     
已邀请:
        您明确指定0,0,0是透明的:
$oTransparentColor = imagecolorallocatealpha( $this->oTransparentCanvas, 0, 0, 0, 127 );
这将应用于图像中三元组为0,0,0的任何像素-换句话说,所有黑色都是您所发现的。 如果您希望原始图像通过,请使用alpha通道进行转换。它在图像中将是一个单独的“图层”,专门为每个像素指定透明度/不透明度。或扫描图像以查找原始图像中未使用的颜色,然后将其指定为新的透明值,而不是默认为0,0,0。     

要回复问题请先登录注册