如何通过脚本修改png图像


How to modify a png image via script?

我有一张透明的png图像,我想复制它,然后裁剪为1x1的透明图像。

我被"裁剪为1x1透明图像"部分卡住了。

我可以修改现有的图像或创建新图像并覆盖现有的图像。我相信这两种选择都会奏效。我只是不确定如何做,并最终与1x1像素透明png图像。

任何帮助都非常感谢。

function convertImage(){
    $file1 = "../myfolder/image.png";
    $file2 = "../myfolder/image-previous.png";
    if (!file_exists($file2)) 
        {
        //make a copy of image.png and name the resulting file image-previous.png
        imagecopy($file2, $file1);
        // convert image.png to a 1x1 pixel transparent png 
        // OR 
        // create a new 1x1 transparent png and overwrite image.png with it
        ???
        }
}

使用PHP为您提供的imagecopyresized方法

关于imagecopyresize的更多信息

的例子:

$image_stats = GetImageSize("/picture/$photo_filename");    
$imagewidth = $image_stats[0];    
$imageheight = $image_stats[1];    
$img_type = $image_stats[2];    
$new_w = $cfg_thumb_width;    
$ratio = ($imagewidth / $cfg_thumb_width);    
$new_h = round($imageheight / $ratio);
// if this is a jpeg, resize as a jpeg
if ($img_type=="2") {    
    $src_img = imagecreatefromjpeg("/picture/$photo_filename");    
    $dst_img = imagecreate($new_w,$new_h);    
    imagecopyresized($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
    imagejpeg($dst_img, "/picture/$photo_filename");
}
// if image is a png, copy it as a png
else if ($img_type=="3") {
    $dst_img=ImageCreate($new_w,$new_h);
    $src_img=ImageCreateFrompng("/picture/$photo_filename");
    imagecopyresized($dst_img,$src_img,0,0,0,0,$new_w,$new_h,ImageSX($src_img),ImageSY($src_img));
    imagepng($dst_img, "/picture/$photo_filename");
}
else ...