2018年11月10日 星期六

準備 WhatsApp 貼紙格式


最近 WhatsApp 推出貼紙功能,特別之處是貼紙不是由內部的商店下載,而是用外部 App 加入。WhatsApp 提供了參考程式,方便大眾自行加入貼紙。不過,貼紙必須為 512x512 像素 PNG 或 WEBP 格式。

我有一些貼紙不是這個格式,於是編寫了 PHP 程式做準備工作:
<?php
//----------------------------------------------------------------------------------------
//  Create a square base transparent image
//----------------------------------------------------------------------------------------
//  Platform: macOS Mojave + PHP
//  Written by Pacess HO
//  Copyright Pacess Studio, 2018.  All rights reserved.
//----------------------------------------------------------------------------------------

$width = 512;
$height = 512;

//----------------------------------------------------------------------------------------
$fileArray = scandir("./");
foreach ($fileArray as $filename)  {

   //  Skip directories
   if ($filename == ".")  {continue;}
   if ($filename == "..")  {continue;}

   $index = strpos($filename, ".png");
   if ($index == false)  {continue;}

   //  This is a PNG file, create output image
   echo("Processing $filename...\n");
   $outputImage = imagecreatetruecolor($width, $height);
   imagealphablending($outputImage, false);
   $color = imagecolorallocatealpha($outputImage, 255, 255, 255, 127);
   imagefilledrectangle($outputImage, 0, 0, $width, $height, $color);
   imagealphablending($outputImage, true);

   //  Get image size
   $size = getimagesize($filename);
   $imageWidth = $size[0];
   $imageHeight = $size[1];

   //  Calculate zoom scale
   $scaleW = $width/$imageWidth;
   $scaleH = $height/$imageHeight;

   $scale = $scaleW;
   if ($scaleW > $scaleH)  {$scale = $scaleH;}
   $zoomWidth = intval($imageWidth*$scale);
   $zoomHeight = intval($imageHeight*$scale);

   //  Put image to output image
   $x = intval(($width-$zoomWidth)/2);
   $y = intval(($height-$zoomHeight)/2);

   $stickerImage = imagecreatefrompng($filename);
   if ($stickerImage == null)  {continue;}
   imagecopyresampled($outputImage, $stickerImage, $x, $y, 0, 0, $zoomWidth, $zoomHeight, $imageWidth, $imageHeight);

   imagealphablending($outputImage, false);
   imagesavealpha($outputImage, true);
   imagepng($outputImage, "_".$filename);
   imagedestroy($outputImage);
}
?>

沒有留言: