如何通过脚本修改png图像?

时间:2011-07-11 19:21:20

标签: php image-manipulation

我有一个透明的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
        ???

        }
}

1 个答案:

答案 0 :(得分:2)

使用PHP为您提供的imagecopyresized方法。

More information about imagecopyresized

示例:

$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 ...