LoginSignup
0
0

More than 5 years have passed since last update.

PHP GDでインデックス透明カラーの8bit PNGを透過ありの32bit PNGに変換する

Posted at

需要はほとんどなさそうですが、インデックス透明カラーが設定されている8bit PNGを透過情報を残して32bit PNGに変換する方法です。

というのも、インデックス透明カラーは、imagecolorsforindexで透明度情報を取得出来ないので、一旦32bit PNGに変換してやろう、という魂胆です。

参考
http://php.net/manual/ja/function.imagecopy.php#73430

<?php
$orgResource = imagepng('path/to/8bit.png');

// 横幅、縦幅を取得する
$width = imagesx($orgResource);
$height = imagesy($orgResource);

// インデックス透明カラーの情報を取得する
$orgTrans = imagecolortransparent($orgResource);
if ($orgTrans >= 0) {
    $orgRgb = imagecolorsforindex($orgResource, $orgTrans);
}

// TrueColorのリソースを用意する
$trueResource = imagecreatetruecolor($width, $height);

// 透明PNGにする
imagealphablending($trueResource, false);
imagesavealpha($trueResource, true);

// TrueColorのリソースに貼り付ける
imagecopy($trueResource, $orgResource, 0, 0, 0, 0, $width, $height);

// インデックス透明カラーがあった場合は、該当の色を透明にする
if ($orgTrans >= 0) {
    for($x=0; $x < $width; $x += 1) {
        for($y=0; $y < $height; $y += 1) {
            $index = imagecolorat($tc, $x, $y);
            $trueRgb = imagecolorsforindex($tc, $index);

            // インデックス透明カラーの情報と比較
            if(
                $orgRgb['red']   === $trueRgb['red'] &&
                $orgRgb['green'] === $trueRgb['green'] &&
                $orgRgb['blue']  === $trueRgb['blue']
            ) {
                // 透明にする(alphaチャンネルを127にする)
                imagesetpixel($trueResource, $x, $y, 127 << 24);
            }
        }
    }
}

// $trueResourceが透過ありの32bit PNG
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0