<?php
class ControllerToolImageCropMask extends Controller{

    public function index()
    {

        $new_image = $this->text_to_image("Deneme");
            //var_dump($new_image); die();
        $source = DIR_IMAGE . 'yellow-slicon.png';
        // Load source and mask
        $source = imagecreatefrompng($source);
        $mask = imagecreatefrompng( $new_image );
        // Apply mask to source
        $this->imagealphamask( $source, $mask );
        // Output
        header( "Content-type: image/png");
        imagepng( $source );




    }

    private function text_to_image($text){

        $font = 25;
        $string = $text;
        $im = @imagecreatetruecolor(strlen($string) * $font / 1.5, $font);
        imagesavealpha($im, true);
        imagealphablending($im, false);
        $white = imagecolorallocatealpha($im, 255, 255, 255, 127);
        imagefill($im, 0, 0, $white);
        $lime = imagecolorallocate($im, 204, 255, 51);
        imagettftext($im, $font, 0, 0, $font - 3, $lime, DIR_IMAGE . "arial.ttf", $string);
        //header("Content-type: image/png");
        imagepng($im, DIR_IMAGE . 'new-png.png');
        imagedestroy($im);

        return DIR_IMAGE . 'new-png.png';

    }

    private function imagealphamask( &$picture, $mask ) {

        // Get sizes and set up new picture
        $xSize = imagesx( $picture );
        $ySize = imagesy( $picture );
        $newPicture = imagecreatetruecolor( $xSize, $ySize );
        imagesavealpha( $newPicture, true );
        imagefill( $newPicture, 0, 0, imagecolorallocatealpha( $newPicture, 0, 0, 0, 127 ) );

        // Resize mask if necessary
        if( $xSize != imagesx( $mask ) || $ySize != imagesy( $mask ) ) {
            $tempPic = imagecreatetruecolor( $xSize, $ySize );
            imagecopyresampled( $tempPic, $mask, 0, 0, 0, 0, $xSize, $ySize, imagesx( $mask ), imagesy( $mask ) );
            imagedestroy( $mask );
            $mask = $tempPic;
        }

        // Perform pixel-based alpha map application
        for( $x = 0; $x < $xSize; $x++ ) {
            for( $y = 0; $y < $ySize; $y++ ) {
                $alpha = imagecolorsforindex( $mask, imagecolorat( $mask, $x, $y ) );
                $alpha = 127 - floor( $alpha[ 'red' ] / 2 );
                $color = imagecolorsforindex( $picture, imagecolorat( $picture, $x, $y ) );
                imagesetpixel( $newPicture, $x, $y, imagecolorallocatealpha( $newPicture, $color[ 'red' ], $color[ 'green' ], $color[ 'blue' ], $alpha ) );
            }
        }

        // Copy back to original picture
        imagedestroy( $picture );
        $picture = $newPicture;
    }

}
