需要はほとんどなさそうですが、インデックス透明カラーが設定されている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