PHP: Converting png's and gif's into grayscale

后端 未结 4 2035
星月不相逢
星月不相逢 2021-01-22 05:49

im using the following script to convert jpgs into grayscale-images. http://bubble.ro/How_to_convert_an_image_to_grayscale_using_PHP.html

i want to upgrade it to also co

4条回答
  •  情歌与酒
    2021-01-22 06:15

    To obtain right pictures without black background you must follow strategy:

    first create your new image item set it's alphablending to false set it's savealpha to true fil it with transparent rectangle copy your grayed picture over it

    your code will be similar to this :

            switch ($handle->file_src_name_ext) {
              case 'gif':
                $sourceIm = imagecreatefromgif($savepath.$handle->file_dst_name);
                break;
              case 'jpg':
                $sourceIm = imagecreatefromjpeg($savepath.$handle->file_dst_name);
                break;
              case 'png':
              default:
                $sourceIm = imagecreatefrompng($savepath.$handle->file_dst_name);
                break;
            }
    
    
            $iw = imagesx($sourceIm);
            $ih = imagesy($sourceIm);
    
            $im = imagecreatetruecolor($iw, $ih);
    
            if (function_exists('imagecolorallocatealpha')) {
                imagealphablending($im, false);
                imagesavealpha($im, true);
                $transparent = imagecolorallocatealpha($im, 255, 255, 255, 127);
                imagefilledrectangle($im, 0, 0, $iw, $ih, $transparent);
            }
            if ($sourceIm ) {
              imagefilter($sourceIm, IMG_FILTER_GRAYSCALE);
            }
            imagecopyresampled($im, $sourceIm, 0, 0, 0, 0, $iw, $ih, $iw, $ih);
            switch ($handle->file_src_name_ext) {
              case 'gif':
                imagepng($im, $savepath.'grd'.$row->id.'.gif');
                break;
              case 'jpg':
                imagejpeg($im, $savepath.'grd'.$row->id.'.jpg');
                break;
              case 'png':
              default:
                imagepng($im, $savepath.'grd'.$row->id.'.png');
                break;
            }
    

    goodluck!


    take a look at my balda pomoshnik

提交回复
热议问题