php 压缩图片,保留图片的像素、透明度

    /**
     * @param  $picture 图片数据流 比如file_get_contents(imageurl)返回的东东
     * @param $destfile 存储路径
     */    
    function miniImg($picture,$destfile)
    {
        //获取源图gd图像标识符
        $srcImg = imagecreatefromstring($picture);
        $srcWidth = imagesx($srcImg);
        $srcHeight = imagesy($srcImg);
        //创建新图
        $newWidth = round($srcWidth / 2);
        $newHeight = round($srcHeight / 2);
        $newImg = imagecreatetruecolor($newWidth, $newHeight);
        //分配颜色 + alpha,将颜色填充到新图上
        $alpha = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
        imagefill($newImg, 0, 0, $alpha);
        
        //将源图拷贝到新图上,并设置在保存 PNG 图像时保存完整的 alpha 通道信息
        imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
        imagesavealpha($newImg, true);
        imagepng($newImg,$destfile);
    }

猜你喜欢

转载自blog.csdn.net/mangrandi/article/details/80758179
今日推荐