Crop resize & watermarking implementation help.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gosu
Forum Newbie
Posts: 19
Joined: Mon Jun 02, 2008 12:17 pm

Crop resize & watermarking implementation help.

Post by gosu »

Hello, Im using the crop function to resize images, but i also want to implement and watermarking of the resized image.
The crop works fine, but i dont know how to implement watermarking.
I will be able to resize image to specified size w/o losing aspect/stretch problems and then will apply transperant frame .png image -> the result will looks like the images in 3dtotal.com on the main page.
Here is the crop:

Code: Select all

/**
 * CropImage Class
 */ 
class fth_cropImage
{ // http://www.findmotive.com/2006/12/13/php-crop-image/
    var $log = '';
    
    function cropImage($nw, $nh, $source, $dest) 
    {
        $size = getimagesize($source);
        $w = $size[0];
        $h = $size[1];
        
        $stypeArr = explode( '.', $source );
        $stype = strtolower( end($stypeArr) );
        
        switch($stype) 
        {
            case 'gif':
                $simg = imagecreatefromgif($source);
                break;
            case 'jpeg':
                $simg = imagecreatefromjpeg($source);
                break;
            case 'jpg':
                $simg = imagecreatefromjpeg($source);
                break;
            case 'png':
                $simg = imagecreatefrompng($source);
                break;
        }
        
        $dimg = imagecreatetruecolor($nw, $nh);
        
        $wm = $w/$nw;
        $hm = $h/$nh;
        
        $h_height = $nh/2;
        $w_height = $nw/2;
        
        if($w> $h) 
        {
            $adjusted_width = $w / $hm;
            $half_width = $adjusted_width / 2;
            $int_width = $half_width - $w_height;
            
            imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
        } 
        elseif( ($w <$h) || ($w == $h) ) 
        {
            $adjusted_height = $h / $wm;
            $half_height = $adjusted_height / 2;
            $int_height = $half_height - $h_height;
            
            imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
        } 
        else 
        {
            imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
        }
        
        imagejpeg($dimg,$dest,85);
    }

Code: Select all

define( 'MM_IMG', ROOT_DIR.'/uploads/main-thumbs/' );
    define( 'MM_HTTP_IMG', $config['http_home_url'].'uploads/main-thumbs/' );
    if (!file_exists(MM_IMG))
    {
        if ( !(@mkdir(MM_IMG, 0777)) ) { return '<br> RNB: Unable to mkdir: "'.MM_IMG.'"'; }
        if ( !(@chmod(MM_IMG, 0777)) ) { return '<br> RNB: Unable to chmod: "'.MM_IMG.'"'; }
    }
 
    $not_resized_image = $img;
    $resized_image = MM_IMG.basename($img);
    if ( 
            ( $size_img = @getimagesize($not_resized_image) ) &&
            (
                ( $size_img[0] > (int)$conf[img_catindex_wigth]) || ($size_img[1] > (int)$conf[img_catindex_hieght]) )
            )
    {
        if (!file_exists( $resized_image ))
        { # make resize:
            $cim = new fth_cropImage;
            $cim->cropImage(    
                                intval($conf[img_catindex_wigth]), 
                                intval($conf[img_catindex_hieght]), 
                                $not_resized_image, 
                                $resized_image 
                            );
            if ( !(@chmod ($resized_image, 0666)) ) { return '<br> MM: Unable to chmod: "'.$resized_image.'"'; }
        }
    }
 
 
So far so good, here is the fun part with the thumb class which also can apply watermark.



And here is the watermarking/image resize class, it can also apply different images according to the $lightness of the image.

Code: Select all

$gd_version = 2;
 
class thumbnail
{
    var $img;
    var $watermark_image_light;
    var $watermark_image_dark;
 
    function thumbnail($imgfile)
    {
        //detect image format
        $this->img['format']=ereg_replace(".*\.(.*)$","\\1",$imgfile);
        $this->img['format']=strtoupper($this->img['format']);
        if ($this->img['format']=="JPG" || $this->img['format']=="JPEG") {
            $this->img['format']="JPEG";
            $this->img['src'] = @imagecreatefromjpeg ($imgfile);
        } elseif ($this->img['format']=="PNG") {
            $this->img['format']="PNG";
            $this->img['src'] = @imagecreatefrompng ($imgfile);
        } elseif ($this->img['format']=="GIF") {
            $this->img['format']="GIF";
            $this->img['src'] = @imagecreatefromgif ($imgfile);
        } else {
            echo "Not Supported File! Thumbnails can only be made from .jpg, gif and .png images!";
            exit();
        }
        $this->img['lebar'] = @imagesx($this->img['src']);
        $this->img['tinggi'] = @imagesy($this->img['src']);
        $this->img['lebar_thumb'] = $this->img['lebar'];
        $this->img['tinggi_thumb'] = $this->img['tinggi'];
        //default quality jpeg
        $this->img['quality']=90;
 
        if ($this->img['src'] == "") {
            echo "Not Supported File! Thumbnails can only be made from .jpg, gif and .png images!";
            @unlink($imgfile);
            exit();
 
        }
    }
 
function size_auto($size=100, $site=0)
{ global $gd_version;
 
    $site = intval($site);
 
    if ($this->img['lebar'] <= $size AND $this->img['tinggi'] <= $size ) {
        $this->img['lebar_thumb'] = $this->img['lebar'];
        $this->img['tinggi_thumb'] = $this->img['tinggi'];
        return 0;
    }
 
 switch ($site) {
 
    case "1" :
        if ($this->img['lebar'] <= $size) 
        {
            $this->img['lebar_thumb'] = $this->img['lebar'];
            $this->img['tinggi_thumb'] = $this->img['tinggi'];
            return 0;
        } else {
            $this->img['lebar_thumb']=$size;
            $this->img['tinggi_thumb'] = ($this->img['lebar_thumb']/$this->img['lebar'])*$this->img['tinggi'];
        }
 
        break;
 
    case "2" :
        if ($this->img['tinggi'] <= $size) 
        {
            $this->img['lebar_thumb'] = $this->img['lebar'];
            $this->img['tinggi_thumb'] = $this->img['tinggi'];
            return 0;
        } else {
            $this->img['tinggi_thumb']=$size;
            $this->img['lebar_thumb'] = ($this->img['tinggi_thumb']/$this->img['tinggi'])*$this->img['lebar'];
        }
 
        break;
 
    default:
 
        if ($this->img['lebar']>=$this->img['tinggi']) 
        {
            $this->img['lebar_thumb']=$size;
            $this->img['tinggi_thumb'] = ($this->img['lebar_thumb']/$this->img['lebar'])*$this->img['tinggi'];
 
        } else {
 
            $this->img['tinggi_thumb']=$size;
            $this->img['lebar_thumb'] = ($this->img['tinggi_thumb']/$this->img['tinggi'])*$this->img['lebar'];
 
        }
 
        break;
  }
 
    if($gd_version==1)
          {
           $this->img['des'] = imagecreate($this->img['lebar_thumb'],$this->img['tinggi_thumb']);
           @imagecopyresized ($this->img['des'], $this->img['src'], 0, 0, 0, 0, $this->img['lebar_thumb'], $this->img['tinggi_thumb'], $this->img['lebar'], $this->img['tinggi']);
          }
    elseif($gd_version==2)
           {
            $this->img['des'] = imagecreatetruecolor($this->img['lebar_thumb'],$this->img['tinggi_thumb']);
            @imagecopyresampled ($this->img['des'], $this->img['src'], 0, 0, 0, 0, $this->img['lebar_thumb'], $this->img['tinggi_thumb'], $this->img['lebar'], $this->img['tinggi']);
            }
 
    $this->img['src'] = $this->img['des'];
    return 1;
}
 
function jpeg_quality($quality=90)
    {
        //jpeg quality
        $this->img['quality']=$quality;
    }
 
function save($save="")
{
 
        if ($this->img['format']=="JPG" || $this->img['format']=="JPEG") {
            //JPEG
            imagejpeg($this->img['src'],"$save",$this->img['quality']);
        } elseif ($this->img['format']=="PNG") {
            //PNG
            imagepng($this->img['src'],"$save");
        } elseif ($this->img['format']=="GIF") {
            //GIF
            imagegif($this->img['src'],"$save");
        }
 
        imagedestroy($this->img['src']);
}
 
 
function show ()
{
        if ($this->img['format']=="JPG" || $this->img['format']=="JPEG") {
            //JPEG
            imageJPEG($this->img['src'],"",$this->img['quality']);
        } elseif ($this->img['format']=="PNG") {
            //PNG
            imagePNG($this->img['src']);
        } elseif ($this->img['format']=="GIF") {
            //GIF
            imageGIF($this->img['src']);
        }
 
        imagedestroy($this->img['src']);
}
 
// *************************************************************************
function insert_watermark($min_image)
    { global $config;
        $margin = 7;
 
        $this->watermark_image_light = ROOT_DIR.'/templates/'.$config['skin'].'/watermark_light.png';
        $this->watermark_image_dark =  ROOT_DIR.'/templates/'.$config['skin'].'/watermark_dark.png';
 
        $image_width = imagesx($this->img['src']);
        $image_height = imagesy($this->img['src']);
 
        list($watermark_width, $watermark_height)
            = getimagesize($this->watermark_image_light);
 
 
                $watermark_x = $image_width - $margin - $watermark_width;
                $watermark_y = $image_height - $margin - $watermark_height;
 
 
        $watermark_x2 = $watermark_x + $watermark_width;
        $watermark_y2 = $watermark_y + $watermark_height;
 
        if ($watermark_x < 0 OR $watermark_y < 0 OR
            $watermark_x2 > $image_width OR $watermark_y2 > $image_height OR
            $image_width < $min_image OR $image_height < $min_image)
        {
           return;
        }
 
 
        $test = imagecreatetruecolor(1, 1);
        imagecopyresampled($test, $this->img['src'], 0, 0, $watermark_x, $watermark_y, 1, 1, $watermark_width, $watermark_height);
        $rgb = imagecolorat($test, 0, 0);
 
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;
 
        $max = min($r, $g, $b);
        $min = max($r, $g, $b);
        $lightness = (double)(($max + $min) / 510.0);
        imagedestroy($test);
 
        $watermark_image = ($lightness < 0.5) ? $this->watermark_image_light : $this->watermark_image_dark;
 
        $watermark = imagecreatefrompng($watermark_image);
 
        imagealphablending($this->img['src'], TRUE);
        imagealphablending($watermark, TRUE);
 
        imagecopy($this->img['src'], $watermark, $watermark_x, $watermark_y, 0, 0,$watermark_width, $watermark_height);
 
        imagedestroy($watermark);
 
    }
 
 
}
 
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Crop resize & watermarking implementation help.

Post by onion2k »

What are you unable to do exactly? You just need to take the output of the first class and input it into the second by the looks of things. What's the problem?





PS. If you're not in a hurry I'm working on an image system that can do exactly what you're looking for. I posted an example the other day... viewtopic.php?p=465516#p465516 Not sure when it'll actually be publicly available though. It's at least a few weeks away, possibly more.
gosu
Forum Newbie
Posts: 19
Joined: Mon Jun 02, 2008 12:17 pm

Re: Crop resize & watermarking implementation help.

Post by gosu »

Yup your project does what i also need. Crop&Resize + watermarking the borders with image (or color).
I don't know how to take the output and use it as input for watermarking... both of the classes i took from the internet,
they both work fine for me, but don't know how to use crop & watermark together. :crazy:
..but hey im new to php :P
gosu
Forum Newbie
Posts: 19
Joined: Mon Jun 02, 2008 12:17 pm

Re: Crop resize & watermarking implementation help.

Post by gosu »

Someone please help on this one, it shouldn't be hard.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Crop resize & watermarking implementation help.

Post by superdezign »

gosu wrote:Someone please help on this one, it shouldn't be hard.
Then do it. -_-

Your code has no comments which means that I'd have to actually read through all of it to determine where you are doing what. If you want help, you have to be specific as to what you want and make it easy to help you. That's likely the reason that you still haven't gotten another response.

I don't know what you have fixed and what you haven't. The most I can do for you is give you a simple function I wrote to add a watermark to an image. Hope it helps.

Code: Select all

/**
 * Watermark image
 * @author LiveWire [Volectricity]
 * @website http://www.volectricity.com
 * @param resource Image
 * @param resource Watermark
 * @param integer Offset x-position
 * @param integer Offset y-position
 * @return resource Watermarked image
 */
function addWatermark($image, $watermark, $offsetX = 0, $offsetY = 0)
{
    // Overlay watermark PNG colors
    for ($x = 0, $width = imagesx($watermark); $x < $width; $x++) {
        for ($y = 0, $height = imagesy($watermark); $y < $height; $y++) {
            $color = imagecolorat($watermark, $x, $y);
            imagesetpixel($image, $x + $offsetX, $y + $offsetY, $color);
        }
    }
    
    return $image;
}
User avatar
lonelywolf
Forum Commoner
Posts: 28
Joined: Tue Jun 10, 2008 6:15 am

Re: Crop resize & watermarking implementation help.

Post by lonelywolf »

hi all! I'm a newcomer. Maybe this code will help you:

Code: Select all

public static function watermark($original_image,$original_watermark,$destination="")
    {
        /*
            create the image from out original image
        */
        $image=imagecreatefromjpeg($original_image);
        /*
            get the image size for watermark resize if neccessary
        */
        list($imagewidth,$imageheight)=getimagesize($original_image);
     
        /*
            create the watermark
        */
        $watermark  =   imagecreatefrompng($original_watermark);            
        /*
            determine the watermark width and height
        */
        list($watermarkwidth,$watermarkheight)=getimagesize($original_watermark);
     
        /*
            if the watermark is bigger than the original image, we simply resize it
        */      
        if($watermarkwidth>$imagewidth || $watermarkheight>$imageheight)
        {
            /*
                some simple resize math
            */
            $water_resize_factor = $imagewidth / $watermarkwidth;
            $new_watermarkwidth  = $watermarkwidth * $water_resize_factor;
            $new_watermarkheight = $watermarkheight * $water_resize_factor;
            /*
                the new watermark creation takes place starting from here
            */          
            $new_watermark = imagecreatetruecolor($new_watermarkwidth , $new_watermarkheight);
            /*
                imagealphablending is important in order to keep 
                our png image (the watewrmark) transparent
            */
            imagealphablending($new_watermark , false);
            imagecopyresampled($new_watermark , $watermark, 0, 0, 0, 0, 
                                                $new_watermarkwidth,$new_watermarkheight, 
                                                $watermarkwidth, $watermarkheight);
            /*
                assign the new values to the old variables
            */
            $watermarkwidth  = $new_watermarkwidth; 
            $watermarkheight = $new_watermarkheight; 
            $watermark       = $new_watermark;
        }
        /*
            we establish the position of the watermark over the image
        */
        $startwidth     =   ($imagewidth    -   $watermarkwidth); 
        $startheight    =   ($imageheight   -   $watermarkheight);
     
        imagecopy($image, $watermark, $startwidth, $startheight, 0, 0, 
                    $watermarkwidth, $watermarkheight); 
        /*
            if we have a destination image, we save it on the server...
        */
        if(!empty($destination))
            imagejpeg($image,$destination);
        /*
            ... else we output the image
        */  
        else 
            imagejpeg($image);
    }
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Crop resize & watermarking implementation help.

Post by onion2k »

@superdezign - Why aren't you using imagecopy() or imagecopymerge()? They'd be a lot quicker.

@gosu - Still think this is easy? :wink:
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Crop resize & watermarking implementation help.

Post by superdezign »

onion2k wrote:@superdezign - Why aren't you using imagecopy() or imagecopymerge()? They'd be a lot quicker.
I tried that originally. I ran into problems with transparencies in *.PNG images when using it (it was either 100% opaque or 100% transparent), so I went with a pixel-by-pixel approach.
gosu
Forum Newbie
Posts: 19
Joined: Mon Jun 02, 2008 12:17 pm

Re: Crop resize & watermarking implementation help.

Post by gosu »

It works, thank you all! You are great :)

source:
Image

result:
Image

I added check for file type of the source image, should be better i suppose?

Code: Select all

class fth_watermark
{
 function watermark($original_image,$original_watermark,$destination="")
    {
        /*  Change here:
            $image=imagecreatefromjpeg($original_image);
            create the image from out original image
        */
        
        $size = getimagesize($original_image);
        $w = $size[0];
        $h = $size[1];
        
        $stypeArr = explode( '.', $original_image );
        $stype = strtolower( end($stypeArr) );
        
        switch($stype) 
        {
            case 'gif':
                $image = imagecreatefromgif($original_image);
                break;
            case 'jpeg':
                $image = imagecreatefromjpeg($original_image);
                break;
            case 'jpg':
                $image = imagecreatefromjpeg($original_image);
                break;
            case 'png':
                $image = imagecreatefrompng($original_image);
                break;
        }
        
        
        
        /*
            get the image size for watermark resize if neccessary
        */
        list($imagewidth,$imageheight)=getimagesize($original_image);
     
        /*
            create the watermark
        */
        $watermark  =   imagecreatefrompng($original_watermark);            
        /*
            determine the watermark width and height
        */
        list($watermarkwidth,$watermarkheight)=getimagesize($original_watermark);
     
        /*
            if the watermark is bigger than the original image, we simply resize it
        */      
        if($watermarkwidth>$imagewidth || $watermarkheight>$imageheight)
        {
            /*
                some simple resize math
            */
            $water_resize_factor = $imagewidth / $watermarkwidth;
            $new_watermarkwidth  = $watermarkwidth * $water_resize_factor;
            $new_watermarkheight = $watermarkheight * $water_resize_factor;
            /*
                the new watermark creation takes place starting from here
            */          
            $new_watermark = imagecreatetruecolor($new_watermarkwidth , $new_watermarkheight);
            /*
                imagealphablending is important in order to keep 
                our png image (the watewrmark) transparent
            */
            imagealphablending($new_watermark , false);
            imagecopyresampled($new_watermark , $watermark, 0, 0, 0, 0, 
                                                $new_watermarkwidth,$new_watermarkheight, 
                                                $watermarkwidth, $watermarkheight);
            /*
                assign the new values to the old variables
            */
            $watermarkwidth  = $new_watermarkwidth; 
            $watermarkheight = $new_watermarkheight; 
            $watermark       = $new_watermark;
        }
        /*
            we establish the position of the watermark over the image
        */
        $startwidth     =   ($imagewidth    -   $watermarkwidth); 
        $startheight    =   ($imageheight   -   $watermarkheight);
     
        imagecopy($image, $watermark, $startwidth, $startheight, 0, 0, 
                    $watermarkwidth, $watermarkheight); 
        /*
            if we have a destination image, we save it on the server...
        */
        if(!empty($destination))
            imagejpeg($image,$destination);
        /*
            ... else we output the image
        */  
        else 
            imagejpeg($image);
    }
 
 
}
 
 
And here is resized image, with size of the source (100x141) smaller than the destination (160x120)and with totally different proportions:
source:
Image

result:
Image
Post Reply