操纵透明PNG会使图像中的所有rgb0,0,0变为透明

如何解决操纵透明PNG会使图像中的所有rgb0,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),#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 );
      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,127 );
    imagefill($this->oTransparentCanvas,$oTransparentColor );

    $bReturnValue = imagecopyresampled( $this->oTransparentCanvas,$this->oTargetImage,$iTargetX,$iTargetY,$this->iCalculatedWidth,$this->iCalculatedHeight,$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,$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\',\'x-png\' );
if( in_array( $this->sSourceExt,$aTransparentTypes ) )
{
  $oTransparentColor = imagecolorallocate( $this->oTargetImage,0 );
  imagecolortransparent( $this->oTargetImage,$oTransparentColor);
  imagealphablending( $this->oTargetImage,false );
}
我不再失去黑色,但是所有现有的透明度都变成了黑色。 我认为问题是我使用黑色作为透明通道。但是如何避免使用图像中的颜色作为透明通道? 感谢任何可以帮助我了解透明度背后的奥秘的人! 吉姆     

解决方法

        您明确指定0,0是透明的:
$oTransparentColor = imagecolorallocatealpha( $this->oTransparentCanvas,127 );
这将应用于图像中三元组为0,0的任何像素-换句话说,所有黑色都是您所发现的。 如果您希望原始图像通过,请使用alpha通道进行转换。它在图像中将是一个单独的“图层”,专门为每个像素指定透明度/不透明度。或扫描图像以查找原始图像中未使用的颜色,然后将其指定为新的透明值,而不是默认为0,0。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-