Nützliche kleine PHP und JavaScript Funktionen

Hi,

Dachte mir es wäre doch schön, wenn wir hier mal unsere nützlichsten kleinen funktionen posten... also solche die mann immer mal wieder braucht und die unabhängig sind.. so könnte man zum einen neues finden, und zum anderen seine funktionen verbessern lassen :D

ich mach auch direckt mal den anfang mit meinen heufig wiederverwerteten funktionen.

PHP:

zur zeit nur eine kleine thumbnail funktion
PHP:
function MkThumbnail($from_file, $to_file, $max_width, $max_height, $quality, $stretch){
    $size = getimagesize ($from_file);
    $ext = strtolower(substr(strrchr($from_file,"."),1));
    if($ext == 'jpg' || $ext == 'jpeg' ){
        $img_temp = imagecreatefromjpeg($from_file);
    }
    if($ext == 'gif'){
        $img_temp = imagecreatefromgif($from_file);
    }
    if($ext == 'png'){
        $img_temp = imagecreatefrompng($from_file);
    }
    if(!$stretch && $size[0] < $max_width && $size[1] < $max_height){
        $max_width = $size[0];
        $max_height = $size[1];
    }
    if($size[0]/$size[1]*$max_height <= $max_width){
        $max_width=imagesx($img_temp)/imagesy($img_temp)*$max_height;
        $img_thumb=imagecreatetruecolor($max_width,$max_height);
    }else{
        $max_height=imagesy($img_temp)/imagesx($img_temp)*$max_width;
        $img_thumb=imagecreatetruecolor($max_width,$max_height);
    }
    imagecopyresampled(
        $img_thumb,$img_temp,
        0,0,0,0,
        $max_width,$max_height, 
        imagesx ($img_temp),imagesy($img_temp)
    );
    if(!$to_file || $to_file == ""){
        header ("Content-type: image/jpeg");
        imagejpeg($img_thumb,'', $quality);
    }else{
        imagejpeg($img_thumb, $to_file, $quality);
    }
    imagedestroy($img_thumb);
    return $to_file;
}
erleuterung:
erstellt vom $from_file (jpg, png oder gif) eine jpg kopie ($to_file) proportional an die $max_width und $max_height angepasst ist.
$quality ist die jpg qüalität der ausgabe datei.
$stretch kann true oder false sein wenn true werden bilder die kleiner als max_height und width sind vergrößert.
wenn bei $to_file false oder nix angegeben wird, wird das bild direckt mit jpg haeder ausgegeben und nicht gespeichert


JavaScript:

meine domredy Funktion
HTML:
<script>
var isInit = false;
window.onDomReady = function(fn){
    if(window.addEventListener){
        window.addEventListener("DOMContentLoaded", fn, false);
    }else if(window.addEvent){
        window.addEvent('domready',fn);
    }else{
        document.onreadystatechange = function(){
            if(document.readyState == "interactive"  || document.readyState == "loaded" || document.readyState == "complete"){
                !isInit ? fn():0;
                isInit = true;                
            }
        }
        }
}
window.onDomReady(funktionsname);
</script>
HTML object größe
HTML:
<script>
function getOBJsize(obj){
    var OBJsize = Array();
    OBJsize['height'] = parseInt(obj.style.height
        || obj.innerHeight  
        || obj.clientHeight 
        || obj.offsetHeight 
        ||0);
    OBJsize['width'] = parseInt(obj.style.width
        || obj.innerWidth 
        || obj.clientWidth 
        || obj.offsetWidth
        ||0);
    return OBJsize;
}
</script>
HTML object position
HTML:
<script>
function getOBJpos(obj){
    var OBJpos = Array();    
    var Tobj = obj;
    OBJpos['top'] = 0;
    while( Tobj != null ) {
        OBJpos['top'] += Tobj.offsetTop;
        Tobj = Tobj.offsetParent;
    }
    var Lobj = obj;
    OBJpos['left'] = 0;
    while( Lobj != null ) {
        OBJpos['left'] += Lobj.offsetLeft;
        Lobj = Lobj.offsetParent;
    }
    return OBJpos;
}
</script>
 
ich hab zur Bild-Manipulation mir mal 'ne komplette Klasse geschrieben:

beinhaltet:

  • Größen-Änderung (mit vielen Optionen - z.B. Seitenverhältnis beibehalten oder nicht, nach längerer oder kürzerer Seite richten, etc.)
  • Rotation
  • Zuschneiden
  • Definieren einer Transparenz-Farbe (incl. Toleranz)
  • Bild-Generierung (z.B. in einer Farbe)
  • Text-Grafik erstellen
  • Wasserzeichen
  • EXIF-Informationen des Original-Bildes anzeigen
  • Bild als JPG oder PNG abspeichern
  • Bild als JPG oder PNG direkt ausgeben


EXIF-Daten im neuen Bild abspeichern funktioniert mit der gdlib leider nicht...

hab das vor langer Zeit mal geschrieben und sicherlich auch noch der ein oder andere kleine Bug drin - aber vielleicht ist es für den ein oder anderen ganz nützlich...

wer Vorschläge für Änderungen/Erweiterungen hat, bitte mir per Mail schreiben (Adresse steht ja im Code)
Wenn ich mal die Zeit finde, werde ich die Klasse nochmal Stück für Stück durchgehen, DocBlocks dazu schreiben, Unit-Tests zu schreiben und ein Interface für Bild-Filter dazu schreiben, auf dass man dann verschiedene Filter-Klassen schreiben kann (z.B. Sepia, Negativ, Gaußscher Weichzeichner etc.) und diese dann auf die Image-Klasse anwenden kann.

PHP:
<?php

/**
 * image-object, where you can edit the image (resize / rotate)
 * works with gdlib!
 * @author Martin Bergann <martin@cs-bergann.de>
 * 
 */
class Image
{
    private $_path;
    private $_img=null;
    private $_infos=null;
    
    private $_error=array();

    private $_exif=array();

    private $_error_msg=array(
    '0'=>'',
    '1'=>'error while loading image',
    '2'=>'error while saving image',
    '3'=>'invalid dimensions',
    '4'=>'no image loaded'
    );


/* Constructor / Destructor */

    public function __construct($path='')
    {
        if(!empty($path))
        $this->loadImage($path);
    }




/* load and save */

    public function loadImage($path)
    {
        $this->_path = $path;
        if(!$this->_infos = @getimagesize($path)){array_push($this->_error,1);return false;}
        
    //    var_dump($this->_infos);
        
        if($this->_infos[2]==1)
        {
            // Bild ist vom Typ gif
            $this->_img = @imagecreatefromgif($this->_path);
        }
        elseif($this->_infos[2]==2)
        {
            // Bild ist vom Typ jpg
            $this->_img = @imagecreatefromjpeg($this->_path);
            $this->_exif = exif_read_data($this->_path, false , true);
        }
        elseif($this->_infos[2]==3)
        {
            // Bild ist vom Typ png
            $this->_img = @imagecreatefrompng($this->_path);
        }
        else
        {
            array_push($this->_error,2);
            return false;
        }

        return true;
    }

    /**
     * saves images by filename-extension
     */
    public function saveImage($path, $quality = 90)
    {
        $dir       = dirname($path);
        $dirName   = basename($dir);
        $parentDir = dirname($dir);
        if (!file_exists($dir)) {
            if (!is_dir($parentDir) || !is_writable($parentDir)) {
                array_push($this->_error,2);
                return false;
            }
            mkdir($dir);
        } elseif (!is_dir($dir) || !is_writable($dir)) {
            array_push($this->_error,2);
            return false;
        }

        switch(strtolower($this->getFilenameExtension($path)))
        {
            case 'jpg':
            case 'jpeg':
                if(!@imagejpeg($this->_img, $path, $quality))
                {
                    array_push($this->_error,2);
                    return false;
                }
                break;
            case 'gif':
                if(!@imagegif($this->_img, $path))
                {
                    array_push($this->_error,2);
                    return false;
                }
                break;
            case 'png':
                if(!@imagepng($this->_img, $path, $quality))
                {
                    array_push($this->_error,2);
                    return false;
                }
                break;
            default:
                break;
        }
        $this->loadImage($path);
        return true;
    }

    public function getExif()
    {
        return $this->_exif;
    }

    public function generateImage($width,$height,$color)
    {
        $this->_img = imagecreatetruecolor($width, $height);
        imagefill($this->_img, 0, 0, $color);
    }

    public function createTextImage($text,$fontfile,$fontsize,$text_color=0xFFFFFF,$background_color=0,$fontangle=0)
    {
        if(!is_numeric($fontsize))
        {
            $fontsize=20;
        }
        if(!is_numeric($fontangle))
        {
            $fontangle = 0;
        }

        //get size of text-field
        $textfield = imagettfbbox($fontsize, $fontangle, $fontfile, $text);
        $text_size_x = (abs($textfield[4] - $textfield[0]) + 10);
        $text_size_y = (abs($textfield[1] - $textfield[7]) + 10);
        $text_pos_x = 3;
        $text_pos_y = $fontsize+5;

        $text_picture = imagecreatetruecolor($text_size_x, $text_size_y);
        
        $t_red=($text_color>>16)&0xFF;
        $t_green=($text_color>>8)&0xFF;
        $t_blue=($text_color)&0xFF;

        $b_red=($background_color>>16)&0xFF;
        $b_green=($background_color>>8)&0xFF;
        $b_blue=($background_color)&0xFF;
        
        $background_color = imagecolorallocate($text_picture, $b_red, $b_green, $b_blue);
        $text_color = imagecolorallocate($text_picture, $t_red, $t_green, $t_blue);

        imagefill($text_picture, 0, 0, $background_color);
        imagettftext($text_picture, $fontsize, $fontangle, $text_pos_x, $text_pos_y, $text_color, $fontfile, $text);
        //if(isset($this->_img))imagedestroy($this->_img);
        $this->_img = $text_picture;
    }

    public function getImageRessource()
    {
        return $this->_img;
    }
    



/* get infos */

    public function getOrigWidth()
    {
        return $this->_infos[0];
    }

    public function getOrigHeight()
    {
        return $this->_infos[1];
    }

    public function getCurrentWidth()
    {
        return (!is_null($this->_img))?imagesx($this->_img):0;
    }

    public function getCurrentHeight()
    {
        return (!is_null($this->_img))?imagesy($this->_img):0;
    }

    public function getOrigMime()
    {
        return $this->_infos['mime'];
    }

    public function getOrigFilenameExtension()
    {
        return $this->getFilenameExtension($this->_path);
    }

    protected function getFilenameExtension($path)
    {
        return preg_replace('/^.*\.([0-9a-z]+)$/i','\\1',$path);
    }

/*Errors*/
    public function hasError()
    {
        return (sizeof($this->_error)!=0);
    }
    
    public function getErrorMsg()
    {
        $r='';
        foreach($this->_error as $errno)
        {
            $r.='Error '.$errno.' : '.$this->_error_msg[$errno].chr(10);
        }
        return $r;
    }


/* manipulate image */
    public function rotate($degree,$bg=0)
    {            
        try
        {
            $img=imagerotate($this->_img,$degree,$bg);
        }
        catch(Exception $e)
        {
            echo $e;
        }

        imagedestroy($this->_img);
        $this->_img=$img;
    }

    /**
     * mode:
     * 0 = use long side to scale and override short side
     * 1 = use short side to scale and override long side
     * 2 = use width to scale and override height
     * 3 = use height to scale and override width
     * --
     * 4 = use width and height - add a black (or any other color) background to fill
     * 5 = use width and height - zoom to the center and cut the rest of the image
     */
    public function resizeProportional($width,$height,$mode=0,$bgcol=0)
    {
        $new_w=0;
        $new_h=0;
        
        if($mode==5)
        {
            $img = imagecreatetruecolor($width,$height);
            imagefill($img,0,0,$bgcol);
            $ratio=$this->getCurrentHeight()/$this->getCurrentWidth();
            $new_ratio=$height/$width;
            if($ratio<$new_ratio)
            {
                //cut left and right
                $new_h=$height;
                $new_w=$height/$ratio;
                $diff=($width-$new_w);
                imagecopyresampled($img,$this->_img,$diff/2,0,0,0,$width-$diff,$height,$this->getCurrentWidth(),$this->getCurrentHeight());
            }
            else
            {
                //cut top and bottom
                $new_w=$width;
                $new_h=$width*$ratio;
                $diff=($height-$new_h);
                imagecopyresampled($img,$this->_img,0,$diff/2,0,0,$width,$height-$diff,$this->getCurrentWidth(),$this->getCurrentHeight());
            }
            imagedestroy($this->_img); /* nötig? */
            $this->_img = $img;
        }
        elseif($mode==4)
        {
            $img = imagecreatetruecolor($width,$height);
            imagefill($img,0,0,$bgcol);
            $ratio=$this->getCurrentHeight()/$this->getCurrentWidth();
            $new_ratio=$height/$width;
            if($new_ratio>$ratio)
            {
                //border at top and bottom
                $new_w=$width;
                $new_h=$width*$ratio;
                $diff=($height-$new_h);
                imagecopyresampled($img,$this->_img,0,$diff/2,0,0,$width,$height-$diff,$this->getCurrentWidth(),$this->getCurrentHeight());
            }
            else
            {
                //border left and right
                $new_h=$height;
                $new_w=$height/$ratio;
                $diff=($width-$new_w);
                imagecopyresampled($img,$this->_img,$diff/2,0,0,0,$width-$diff,$height,$this->getCurrentWidth(),$this->getCurrentHeight());
            }
            imagedestroy($this->_img); /* nötig? */
            $this->_img = $img;
        }
        elseif($mode==3 || ($mode==0 && $this->getCurrentHeight()>=$this->getCurrentWidth()) || ($mode==1 && $this->getCurrentHeight()<=$this->getCurrentWidth()))
        {
            $ratio=$this->getCurrentWidth()/$this->getCurrentHeight();
            $new_h=$height;
            $new_w=$ratio*$height;
            $this->resize($new_w,$new_h);
        }
        else
        {
            $ratio=$this->getCurrentHeight()/$this->getCurrentWidth();
            $new_w=$width;
            $new_h=$ratio*$width;
            $this->resize($new_w,$new_h);
        }
    }

    public function resize($width,$height)
    {
        if(!is_numeric($width)||$width<=0||!is_numeric($height)||$height<=0)
        {
            array_push($this->_error,3);
            return false;
        }
        $img = imagecreatetruecolor($width,$height);
        imagecopyresampled($img,$this->_img,0,0,0,0,$width,$height,$this->getCurrentWidth(),$this->getCurrentHeight());
        imagedestroy($this->_img); /* nötig? */
        $this->_img = $img;
    }

    public function crop($top,$left,$bottom,$right)
    {
        $nw=($right-$left);
        $nh=($bottom-$top);
        $img = imagecreatetruecolor($nw,$nh);
        imagecopyresampled($img,$this->_img,0,0,$left,$top,$nw,$nh,$nw,$nh);
        imagedestroy($this->_img);
        $this->_img=$img;
    }

    public function setTransparentColor($transparentColor,$toleranz=10)
    {
        if(is_null($this->_img))
        {
            array_push($this->_error,4);
            return false;
        }
        //split index to red green and blue:
        $t_red=($transparentColor>>16)&0xFF;
        $t_green=($transparentColor>>8)&0xFF;
        $t_blue=($transparentColor)&0xFF;
/* info:
 *     combining the three colors to the color-index:
 *     $transparentColor=($t_red<<16)|($t_green<<8)|($t_blue);
*/

        //fill all pixel within a defined tolerance with the transparentColor
        for ($ix = 0; $ix < $this->getCurrentWidth(); $ix++)
        {
            for ($iy = 0; $iy < $this->getCurrentHeight(); $iy++)
            {
                $farbindex = imagecolorat($this->_img, $ix, $iy);
                $p_red=($farbindex>>16)&0xFF;
                $p_green=($farbindex>>8)&0xFF;
                $p_blue=($farbindex)&0xFF;
                if(($p_red>=($t_red-$toleranz) && $p_red<=$t_red+$toleranz) && ($p_green>=($t_green-$toleranz) && $p_green<=$t_green+$toleranz) && ($p_blue>=($t_blue-$toleranz) && $p_blue<=$t_blue+$toleranz))
                {
                    imagesetpixel ($this->_img, $ix, $iy, $transparentColor);
                }
            }
        }

        imagecolortransparent($this->_img,$transparentColor);
    }

    public function addWatermarkImageObject($ImageObject,$opacity=50,$posX=null,$posY=null)
    {
        if(is_null($posX))
            $posX = $this->getCurrentWidth() / 2 - ($ImageObject->getCurrentWidth() / 2);
        if(is_null($posY))
            $posY = $this->getCurrentHeight() / 2 - ($ImageObject->getCurrentHeight() / 2);
        if(is_null($this->_img))
        {
            array_push($this->_error,4);
            return false;
        }
        imagecopymerge($this->_img, $ImageObject->getImageRessource(), $posX, $posY, 0, 0, $ImageObject->getCurrentWidth(), $ImageObject->getCurrentHeight(), $opacity);
    }

    public function addWatermarkImageRessource($Image,$opacity=50,$posX=null,$posY=null)
    {
        if(is_null($posX))
            $posX = $this->getCurrentWidth() / 2 - (imagesx($Image) / 2);
        if(is_null($posY))
            $posY = $this->getCurrentHeight() / 2 - (imagesx($Image) / 2);
        if(is_null($this->_img))
        {
            array_push($this->_error,4);
            return false;
        }
        imagecopymerge($this->_img, $Image, $posX, $posY, 0, 0, imagesx($Image), imagesx($Image), $opacity);
    }

    public function addWatermark($watermarkFile,$opacity=50,$posX=null,$posY=null,$angle=0,$transparentColor=null,$resizeW=null,$resizeH=null,$resizeMode=null)
    {

        $watermark=new Image($watermarkFile);

        if(is_null($resizeMode))
        {
            if(!is_null($resizeW) && !is_null($resizeH))
                $watermark->resize($resizeW,$resizeH);
        }
        else
        {
            if(!is_null($resizeW) && !is_null($resizeH))
            $watermark->resizeProportional($resizeW,$resizeH,$resizeMode);
        }
        //im Fehler-Fall beenden
        if($watermark->hasError()) return false;

        $watermark->rotate($angle,$transparentColor);
        $watermark->setTransparentColor($transparentColor);
        $this->addWatermarkImageObject($watermark,$opacity,$posX,$posY);

    }
    
    public function showJPG()
    {
        if(is_null($this->_img))
        {
            array_push($this->_error,4);
            return false;
        }
        header('Content-type: image/jpeg');
        imagejpeg($this->_img);
    }

    public function showPNG()
    {
        if(is_null($this->_img))
        {
            array_push($this->_error,4);
            return false;
        }
        header('Content-type: image/png');
        imagepng($this->_img);
    }
}

viel Spaß damit! :-)
 
Bevor jeder seine eigenen Funktionen für grundlegende Dinge schreibt, sollte man sich überlegen ein Framework zu verwenden. Gute Programmierer schreiben guten Code, bessere Programmierer greifen auf sehr guten ausgereiften Code zurück.

Zum Beispiel ist das Framework CodeIgniter für PHP-Projekte sehr nützlich.
http://de.wikipedia.org/wiki/CodeIgniter
 
Bevor jeder seine eigenen Funktionen für grundlegende Dinge schreibt, sollte man sich überlegen ein Framework zu verwenden. Gute Programmierer schreiben guten Code, bessere Programmierer greifen auf sehr guten ausgereiften Code zurück.

das stimmt schon... nur ist es für sehr kleine projekte oft nicht nötig ein framework zu nehmen, und ausserdem ist es interessant zu sehen wie die funktionen wirklich laufen ... nacher können die programierer nurnoch mit frameworks umgehen und keiner weis mehr wohers kommt ...

mich interessierts ;)
 
das stimmt schon... nur ist es für sehr kleine projekte oft nicht nötig ein framework zu nehmen, und ausserdem ist es interessant zu sehen wie die funktionen wirklich laufen ... nacher können die programierer nurnoch mit frameworks umgehen und keiner weis mehr wohers kommt ...

Jein. Wenn man bereits von einem "Projekt" sprechen kann, kann man ruhig zu CodeIgniter greifen. Wenn man wissen will wie eine Funktion implementiert ist, schaut man einfach in die jeweilige Funktion rein. In C/C++ artete das selbstmachen soweit aus, dass jede Library eigene Stringfunktionen neu implementierte.
 
Ich bin da auch der Meinung von mauralix - man sollte das Rad nicht ständig neu erfinden. Für PHP gibts bereits einige sehr gute Frameworks wie beispielsweise Kohanna und CodeIgniter - letzteres wurde ja bereits genannt. Es muss nicht immer gleich Zend sein.

Diese Frameworks sind sinnvollerweise so aufgebaut, dass man seine eigenen generischen Funktionen oder Klassen in Form von Plugins oder Libraries der jeweiligen Community wieder zur Verfügung stellen kann.

Für Javascript kann ich Mootools sehr empfehlen. Absolut modular aufgebaut & 100% flexibel. Neben den offiziellen Plugins gibt es auch ein übersichtliches Verzeichnis in das Entwickler ihren Plugins eintragen können. Das macht es sehr einfach, entsprechenden Code zu finden und wieder zu verwenden.

In den meisten Fällen lohnt es sich einen Blick in den Sourcecode des jeweiligen Frameworks zu werfen. Es ist echt interessant und man kann dabei jede Menge lernen!

Bei 3rd Party Plugins ist es meiner Meinung nach sogar Pflicht, sich vorher mal den Source zumidnest grob durchzuschauen. Schließlich weiß man nie, was man sich damit ins Haus holt ;-) Normalerweise merkt man dann recht schnell, ob der Autor fähig ist oder eben nicht.
 
ich hab zur Bild-Manipulation mir mal 'ne komplette Klasse geschrieben:

beinhaltet:

  • Größen-Änderung (mit vielen Optionen - z.B. Seitenverhältnis beibehalten oder nicht, nach längerer oder kürzerer Seite richten, etc.)
  • Rotation
  • Zuschneiden
  • Definieren einer Transparenz-Farbe (incl. Toleranz)
  • Bild-Generierung (z.B. in einer Farbe)
  • Text-Grafik erstellen
  • Wasserzeichen
  • EXIF-Informationen des Original-Bildes anzeigen
  • Bild als JPG oder PNG abspeichern
  • Bild als JPG oder PNG direkt ausgeben


EXIF-Daten im neuen Bild abspeichern funktioniert mit der gdlib leider nicht...

hab das vor langer Zeit mal geschrieben und sicherlich auch noch der ein oder andere kleine Bug drin - aber vielleicht ist es für den ein oder anderen ganz nützlich...

wer Vorschläge für Änderungen/Erweiterungen hat, bitte mir per Mail schreiben (Adresse steht ja im Code)
Wenn ich mal die Zeit finde, werde ich die Klasse nochmal Stück für Stück durchgehen, DocBlocks dazu schreiben, Unit-Tests zu schreiben und ein Interface für Bild-Filter dazu schreiben, auf dass man dann verschiedene Filter-Klassen schreiben kann (z.B. Sepia, Negativ, Gaußscher Weichzeichner etc.) und diese dann auf die Image-Klasse anwenden kann.

PHP:
<?php

/**
 * image-object, where you can edit the image (resize / rotate)
 * works with gdlib!
 * @author Martin Bergann <martin@cs-bergann.de>
 * 
 */
class Image
{
    private $_path;
    private $_img=null;
    private $_infos=null;
    
    private $_error=array();

    private $_exif=array();

    private $_error_msg=array(
    '0'=>'',
    '1'=>'error while loading image',
    '2'=>'error while saving image',
    '3'=>'invalid dimensions',
    '4'=>'no image loaded'
    );


/* Constructor / Destructor */

    public function __construct($path='')
    {
        if(!empty($path))
        $this->loadImage($path);
    }




/* load and save */

    public function loadImage($path)
    {
        $this->_path = $path;
        if(!$this->_infos = @getimagesize($path)){array_push($this->_error,1);return false;}
        
    //    var_dump($this->_infos);
        
        if($this->_infos[2]==1)
        {
            // Bild ist vom Typ gif
            $this->_img = @imagecreatefromgif($this->_path);
        }
        elseif($this->_infos[2]==2)
        {
            // Bild ist vom Typ jpg
            $this->_img = @imagecreatefromjpeg($this->_path);
            $this->_exif = exif_read_data($this->_path, false , true);
        }
        elseif($this->_infos[2]==3)
        {
            // Bild ist vom Typ png
            $this->_img = @imagecreatefrompng($this->_path);
        }
        else
        {
            array_push($this->_error,2);
            return false;
        }

        return true;
    }

    /**
     * saves images by filename-extension
     */
    public function saveImage($path, $quality = 90)
    {
        $dir       = dirname($path);
        $dirName   = basename($dir);
        $parentDir = dirname($dir);
        if (!file_exists($dir)) {
            if (!is_dir($parentDir) || !is_writable($parentDir)) {
                array_push($this->_error,2);
                return false;
            }
            mkdir($dir);
        } elseif (!is_dir($dir) || !is_writable($dir)) {
            array_push($this->_error,2);
            return false;
        }

        switch(strtolower($this->getFilenameExtension($path)))
        {
            case 'jpg':
            case 'jpeg':
                if(!@imagejpeg($this->_img, $path, $quality))
                {
                    array_push($this->_error,2);
                    return false;
                }
                break;
            case 'gif':
                if(!@imagegif($this->_img, $path))
                {
                    array_push($this->_error,2);
                    return false;
                }
                break;
            case 'png':
                if(!@imagepng($this->_img, $path, $quality))
                {
                    array_push($this->_error,2);
                    return false;
                }
                break;
            default:
                break;
        }
        $this->loadImage($path);
        return true;
    }

    public function getExif()
    {
        return $this->_exif;
    }

    public function generateImage($width,$height,$color)
    {
        $this->_img = imagecreatetruecolor($width, $height);
        imagefill($this->_img, 0, 0, $color);
    }

    public function createTextImage($text,$fontfile,$fontsize,$text_color=0xFFFFFF,$background_color=0,$fontangle=0)
    {
        if(!is_numeric($fontsize))
        {
            $fontsize=20;
        }
        if(!is_numeric($fontangle))
        {
            $fontangle = 0;
        }

        //get size of text-field
        $textfield = imagettfbbox($fontsize, $fontangle, $fontfile, $text);
        $text_size_x = (abs($textfield[4] - $textfield[0]) + 10);
        $text_size_y = (abs($textfield[1] - $textfield[7]) + 10);
        $text_pos_x = 3;
        $text_pos_y = $fontsize+5;

        $text_picture = imagecreatetruecolor($text_size_x, $text_size_y);
        
        $t_red=($text_color>>16)&0xFF;
        $t_green=($text_color>>8)&0xFF;
        $t_blue=($text_color)&0xFF;

        $b_red=($background_color>>16)&0xFF;
        $b_green=($background_color>>8)&0xFF;
        $b_blue=($background_color)&0xFF;
        
        $background_color = imagecolorallocate($text_picture, $b_red, $b_green, $b_blue);
        $text_color = imagecolorallocate($text_picture, $t_red, $t_green, $t_blue);

        imagefill($text_picture, 0, 0, $background_color);
        imagettftext($text_picture, $fontsize, $fontangle, $text_pos_x, $text_pos_y, $text_color, $fontfile, $text);
        //if(isset($this->_img))imagedestroy($this->_img);
        $this->_img = $text_picture;
    }

    public function getImageRessource()
    {
        return $this->_img;
    }
    



/* get infos */

    public function getOrigWidth()
    {
        return $this->_infos[0];
    }

    public function getOrigHeight()
    {
        return $this->_infos[1];
    }

    public function getCurrentWidth()
    {
        return (!is_null($this->_img))?imagesx($this->_img):0;
    }

    public function getCurrentHeight()
    {
        return (!is_null($this->_img))?imagesy($this->_img):0;
    }

    public function getOrigMime()
    {
        return $this->_infos['mime'];
    }

    public function getOrigFilenameExtension()
    {
        return $this->getFilenameExtension($this->_path);
    }

    protected function getFilenameExtension($path)
    {
        return preg_replace('/^.*\.([0-9a-z]+)$/i','\\1',$path);
    }

/*Errors*/
    public function hasError()
    {
        return (sizeof($this->_error)!=0);
    }
    
    public function getErrorMsg()
    {
        $r='';
        foreach($this->_error as $errno)
        {
            $r.='Error '.$errno.' : '.$this->_error_msg[$errno].chr(10);
        }
        return $r;
    }


/* manipulate image */
    public function rotate($degree,$bg=0)
    {            
        try
        {
            $img=imagerotate($this->_img,$degree,$bg);
        }
        catch(Exception $e)
        {
            echo $e;
        }

        imagedestroy($this->_img);
        $this->_img=$img;
    }

    /**
     * mode:
     * 0 = use long side to scale and override short side
     * 1 = use short side to scale and override long side
     * 2 = use width to scale and override height
     * 3 = use height to scale and override width
     * --
     * 4 = use width and height - add a black (or any other color) background to fill
     * 5 = use width and height - zoom to the center and cut the rest of the image
     */
    public function resizeProportional($width,$height,$mode=0,$bgcol=0)
    {
        $new_w=0;
        $new_h=0;
        
        if($mode==5)
        {
            $img = imagecreatetruecolor($width,$height);
            imagefill($img,0,0,$bgcol);
            $ratio=$this->getCurrentHeight()/$this->getCurrentWidth();
            $new_ratio=$height/$width;
            if($ratio<$new_ratio)
            {
                //cut left and right
                $new_h=$height;
                $new_w=$height/$ratio;
                $diff=($width-$new_w);
                imagecopyresampled($img,$this->_img,$diff/2,0,0,0,$width-$diff,$height,$this->getCurrentWidth(),$this->getCurrentHeight());
            }
            else
            {
                //cut top and bottom
                $new_w=$width;
                $new_h=$width*$ratio;
                $diff=($height-$new_h);
                imagecopyresampled($img,$this->_img,0,$diff/2,0,0,$width,$height-$diff,$this->getCurrentWidth(),$this->getCurrentHeight());
            }
            imagedestroy($this->_img); /* nötig? */
            $this->_img = $img;
        }
        elseif($mode==4)
        {
            $img = imagecreatetruecolor($width,$height);
            imagefill($img,0,0,$bgcol);
            $ratio=$this->getCurrentHeight()/$this->getCurrentWidth();
            $new_ratio=$height/$width;
            if($new_ratio>$ratio)
            {
                //border at top and bottom
                $new_w=$width;
                $new_h=$width*$ratio;
                $diff=($height-$new_h);
                imagecopyresampled($img,$this->_img,0,$diff/2,0,0,$width,$height-$diff,$this->getCurrentWidth(),$this->getCurrentHeight());
            }
            else
            {
                //border left and right
                $new_h=$height;
                $new_w=$height/$ratio;
                $diff=($width-$new_w);
                imagecopyresampled($img,$this->_img,$diff/2,0,0,0,$width-$diff,$height,$this->getCurrentWidth(),$this->getCurrentHeight());
            }
            imagedestroy($this->_img); /* nötig? */
            $this->_img = $img;
        }
        elseif($mode==3 || ($mode==0 && $this->getCurrentHeight()>=$this->getCurrentWidth()) || ($mode==1 && $this->getCurrentHeight()<=$this->getCurrentWidth()))
        {
            $ratio=$this->getCurrentWidth()/$this->getCurrentHeight();
            $new_h=$height;
            $new_w=$ratio*$height;
            $this->resize($new_w,$new_h);
        }
        else
        {
            $ratio=$this->getCurrentHeight()/$this->getCurrentWidth();
            $new_w=$width;
            $new_h=$ratio*$width;
            $this->resize($new_w,$new_h);
        }
    }

    public function resize($width,$height)
    {
        if(!is_numeric($width)||$width<=0||!is_numeric($height)||$height<=0)
        {
            array_push($this->_error,3);
            return false;
        }
        $img = imagecreatetruecolor($width,$height);
        imagecopyresampled($img,$this->_img,0,0,0,0,$width,$height,$this->getCurrentWidth(),$this->getCurrentHeight());
        imagedestroy($this->_img); /* nötig? */
        $this->_img = $img;
    }

    public function crop($top,$left,$bottom,$right)
    {
        $nw=($right-$left);
        $nh=($bottom-$top);
        $img = imagecreatetruecolor($nw,$nh);
        imagecopyresampled($img,$this->_img,0,0,$left,$top,$nw,$nh,$nw,$nh);
        imagedestroy($this->_img);
        $this->_img=$img;
    }

    public function setTransparentColor($transparentColor,$toleranz=10)
    {
        if(is_null($this->_img))
        {
            array_push($this->_error,4);
            return false;
        }
        //split index to red green and blue:
        $t_red=($transparentColor>>16)&0xFF;
        $t_green=($transparentColor>>8)&0xFF;
        $t_blue=($transparentColor)&0xFF;
/* info:
 *     combining the three colors to the color-index:
 *     $transparentColor=($t_red<<16)|($t_green<<8)|($t_blue);
*/

        //fill all pixel within a defined tolerance with the transparentColor
        for ($ix = 0; $ix < $this->getCurrentWidth(); $ix++)
        {
            for ($iy = 0; $iy < $this->getCurrentHeight(); $iy++)
            {
                $farbindex = imagecolorat($this->_img, $ix, $iy);
                $p_red=($farbindex>>16)&0xFF;
                $p_green=($farbindex>>8)&0xFF;
                $p_blue=($farbindex)&0xFF;
                if(($p_red>=($t_red-$toleranz) && $p_red<=$t_red+$toleranz) && ($p_green>=($t_green-$toleranz) && $p_green<=$t_green+$toleranz) && ($p_blue>=($t_blue-$toleranz) && $p_blue<=$t_blue+$toleranz))
                {
                    imagesetpixel ($this->_img, $ix, $iy, $transparentColor);
                }
            }
        }

        imagecolortransparent($this->_img,$transparentColor);
    }

    public function addWatermarkImageObject($ImageObject,$opacity=50,$posX=null,$posY=null)
    {
        if(is_null($posX))
            $posX = $this->getCurrentWidth() / 2 - ($ImageObject->getCurrentWidth() / 2);
        if(is_null($posY))
            $posY = $this->getCurrentHeight() / 2 - ($ImageObject->getCurrentHeight() / 2);
        if(is_null($this->_img))
        {
            array_push($this->_error,4);
            return false;
        }
        imagecopymerge($this->_img, $ImageObject->getImageRessource(), $posX, $posY, 0, 0, $ImageObject->getCurrentWidth(), $ImageObject->getCurrentHeight(), $opacity);
    }

    public function addWatermarkImageRessource($Image,$opacity=50,$posX=null,$posY=null)
    {
        if(is_null($posX))
            $posX = $this->getCurrentWidth() / 2 - (imagesx($Image) / 2);
        if(is_null($posY))
            $posY = $this->getCurrentHeight() / 2 - (imagesx($Image) / 2);
        if(is_null($this->_img))
        {
            array_push($this->_error,4);
            return false;
        }
        imagecopymerge($this->_img, $Image, $posX, $posY, 0, 0, imagesx($Image), imagesx($Image), $opacity);
    }

    public function addWatermark($watermarkFile,$opacity=50,$posX=null,$posY=null,$angle=0,$transparentColor=null,$resizeW=null,$resizeH=null,$resizeMode=null)
    {

        $watermark=new Image($watermarkFile);

        if(is_null($resizeMode))
        {
            if(!is_null($resizeW) && !is_null($resizeH))
                $watermark->resize($resizeW,$resizeH);
        }
        else
        {
            if(!is_null($resizeW) && !is_null($resizeH))
            $watermark->resizeProportional($resizeW,$resizeH,$resizeMode);
        }
        //im Fehler-Fall beenden
        if($watermark->hasError()) return false;

        $watermark->rotate($angle,$transparentColor);
        $watermark->setTransparentColor($transparentColor);
        $this->addWatermarkImageObject($watermark,$opacity,$posX,$posY);

    }
    
    public function showJPG()
    {
        if(is_null($this->_img))
        {
            array_push($this->_error,4);
            return false;
        }
        header('Content-type: image/jpeg');
        imagejpeg($this->_img);
    }

    public function showPNG()
    {
        if(is_null($this->_img))
        {
            array_push($this->_error,4);
            return false;
        }
        header('Content-type: image/png');
        imagepng($this->_img);
    }
}

viel Spaß damit! :-)

Unter welcher Lizenz steht das denn?
 
Zurück
Oben