Hackerboard Wiki HaboBlog
Hackerboard bei Facebook Hackerboard bei Google+ Hackerboard bei Twitter

[HaBo]

 
(Web-) Design und webbasierte Sprachen Tipps & Tricks, Designabgleich, HTML & Javascript, Flash, ASP, PHP, Perl/CGI...

Nützliche kleine PHP und JavaScript Funktionen

Diskussion: Nützliche kleine PHP und JavaScript Funktionen im Forum (Web-) Design und webbasierte Sprachen, in der Kategorie Web, Network & Multimedia Palace; Anzeige Hi, Dachte mir es wäre doch schön, wenn wir hier mal unsere nützlichsten kleinen funktionen posten... also solche die ...

Antwort
Alt 09.12.10, 13:45   #1 (permalink)
 
Registriert seit: 03.07.10
ronco Leistung: Facit NTK
Likes: 0
Standard Nützliche kleine PHP und JavaScript Funktionen

Anzeige

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

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

PHP:

zur zeit nur eine kleine thumbnail funktion

PHP-Code:
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-Code:
<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-Code:
<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-Code:
<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>
ronco ist offline   Mit Zitat antworten
Alt 09.12.10, 14:03   #2 (permalink)
Member of Honour
 
Benutzerbild von beavisbee
 
Registriert seit: 22.02.07
beavisbee Leistung: Pentium IIIbeavisbee Leistung: Pentium IIIbeavisbee Leistung: Pentium IIIbeavisbee Leistung: Pentium III
beavisbee eine Nachricht über ICQ schicken
Likes: 77
Standard

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.

image.class.php   

PHP-Code:
<?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->_pathfalse 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->_img00$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_picture00$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==|| ($mode==&& $this->getCurrentHeight()>=$this->getCurrentWidth()) || ($mode==&& $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() / - ($ImageObject->getCurrentWidth() / 2);
        if(
is_null($posY))
            
$posY $this->getCurrentHeight() / - ($ImageObject->getCurrentHeight() / 2);
        if(
is_null($this->_img))
        {
            
array_push($this->_error,4);
            return 
false;
        }
        
imagecopymerge($this->_img$ImageObject->getImageRessource(), $posX$posY00$ImageObject->getCurrentWidth(), $ImageObject->getCurrentHeight(), $opacity);
    }

    public function 
addWatermarkImageRessource($Image,$opacity=50,$posX=null,$posY=null)
    {
        if(
is_null($posX))
            
$posX $this->getCurrentWidth() / - (imagesx($Image) / 2);
        if(
is_null($posY))
            
$posY $this->getCurrentHeight() / - (imagesx($Image) / 2);
        if(
is_null($this->_img))
        {
            
array_push($this->_error,4);
            return 
false;
        }
        
imagecopymerge($this->_img$Image$posX$posY00imagesx($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! :-)
beavisbee ist gerade online   Mit Zitat antworten
   
HaBOT
 
- Anzeige -

Werbung ist gerade online    
Alt 09.12.10, 19:52   #3 (permalink)
 
Benutzerbild von mauralix
 
Registriert seit: 17.04.06
mauralix Leistung: 8086
Likes: 3
Standard

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
mauralix ist offline   Mit Zitat antworten
Alt 09.12.10, 22:59   #4 (permalink)
Themenstarter
 
Registriert seit: 03.07.10
ronco Leistung: Facit NTK
Likes: 0
Standard

Zitat:
Zitat von mauralix Beitrag anzeigen
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
ronco ist offline   Mit Zitat antworten
Alt 09.12.10, 23:17   #5 (permalink)
 
Benutzerbild von mauralix
 
Registriert seit: 17.04.06
mauralix Leistung: 8086
Likes: 3
Standard

Zitat:
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.
mauralix ist offline   Mit Zitat antworten
Alt 12.12.10, 22:59   #6 (permalink)
404
 
Benutzerbild von 404
 
Registriert seit: 28.11.04
404 Leistung: Z3
404 eine Nachricht über ICQ schicken
Likes: 0
Talking

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.
__________________
Major Fault, General Error and Colonel Panic came together to celebrate timeout.


------------------------------------------------
http://www.shick.de/
------------------------------------------------
404 ist offline   Mit Zitat antworten
Alt 13.12.10, 20:48   #7 (permalink)
Member of Honour
 
Benutzerbild von Brabax
 
Registriert seit: 04.10.01
Brabax Leistung: 8086Brabax Leistung: 8086
Brabax eine Nachricht über ICQ schicken
Likes: 42
Standard

Ich stehe auch mehr auf das DIY-Verfahren - macht doch auch viel mehr Spaß
__________________

<< Wir leben bereits im morgigen Gestern, doch vom gestrigen Morgen sind wir noch weit entfernt. >>

<< Träume sind Schäume. Es liegt an dir ob du sie lebst oder ein Schaumschläger bist! >>

<< Erst wenn man beginnt zu implizieren, wird man merken, dass einem sowieso keiner richtig zuhört. >>
Brabax ist offline   Mit Zitat antworten
Alt 14.06.11, 23:09   #8 (permalink)
Senior Member
 
Registriert seit: 13.07.08
enkore Leistung: K 6-3enkore Leistung: K 6-3enkore Leistung: K 6-3
Likes: 85
Standard

Zitat:
Zitat von beavisbee Beitrag anzeigen
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.

image.class.php   

PHP-Code:
<?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->_pathfalse 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->_img00$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_picture00$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==|| ($mode==&& $this->getCurrentHeight()>=$this->getCurrentWidth()) || ($mode==&& $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() / - ($ImageObject->getCurrentWidth() / 2);
        if(
is_null($posY))
            
$posY $this->getCurrentHeight() / - ($ImageObject->getCurrentHeight() / 2);
        if(
is_null($this->_img))
        {
            
array_push($this->_error,4);
            return 
false;
        }
        
imagecopymerge($this->_img$ImageObject->getImageRessource(), $posX$posY00$ImageObject->getCurrentWidth(), $ImageObject->getCurrentHeight(), $opacity);
    }

    public function 
addWatermarkImageRessource($Image,$opacity=50,$posX=null,$posY=null)
    {
        if(
is_null($posX))
            
$posX $this->getCurrentWidth() / - (imagesx($Image) / 2);
        if(
is_null($posY))
            
$posY $this->getCurrentHeight() / - (imagesx($Image) / 2);
        if(
is_null($this->_img))
        {
            
array_push($this->_error,4);
            return 
false;
        }
        
imagecopymerge($this->_img$Image$posX$posY00imagesx($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?
__________________
"It is the human race! The deterioration of the spirit of man. Man undermining himself, causing a self-willed, self-imposed, self-evident self-destruction."
+++ BREAKING +++ Troll ertrinkt im Planschbecken +++
enkore ist offline   Mit Zitat antworten
Antwort
   
- Anzeige -

Werbung ist gerade online    

[HaBo] » Web, Network & Multimedia Palace » (Web-) Design und webbasierte Sprachen » Nützliche kleine PHP und JavaScript Funktionen
Themen-Optionen
Ansicht

Forumregeln
Es ist Ihnen nicht erlaubt, neue Themen zu verfassen.
Es ist Ihnen nicht erlaubt, auf Beiträge zu antworten.
Es ist Ihnen nicht erlaubt, Anhänge hochzuladen.
Es ist Ihnen nicht erlaubt, Ihre Beiträge zu bearbeiten.

BB-Code ist an.
Smileys sind an.
[IMG] Code ist an.
HTML-Code ist aus.
Trackbacks sind aus
Pingbacks sind aus
Refbacks sind aus



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61