Avatar billede rhandersen Nybegynder
02. oktober 2004 - 07:55 Der er 2 kommentarer og
1 løsning

Redigere i billeder ved upload i PHP

Hvordan er det nu man kan redigerer i billeder ved upload i php?

Jeg skal fx have lavet så et billede bliver kvadratisk i php, ved at den går ud fra midten og cropper den så den er lige så bred som den er høj. Altså så det bliver midten af billedet man ser.

Og så skal jeg have lavet en funktion der resizer et billede.
Vil i eksperter lave det for mig?`

Mvh Rasmus
Avatar billede jakobdo Ekspert
02. oktober 2004 - 09:59 #1
En søgning på resize her på eksperten (Katetori: php), gav mig følgende:

http://eksperten.dk/spm/449302
Måske den tråd var et kig værd?
Avatar billede rhandersen Nybegynder
02. oktober 2004 - 10:14 #2
Jeg vil gerne have en til at lave et komplet script til mig, og vi går bare ud fra at den skal resize og croppe et billede ved navn hus.jpg som ligger i imageedit
Avatar billede michaelb.dk Nybegynder
02. oktober 2004 - 11:31 #3
Her er scriptet du skal bruge.
Opret en mappe der hedder billeder (f.eks.) og læg nedenstående fil deri. Opret en undermappe der hedder tumb og fix den til 777. Når du, fra index.php, uploader et billede bliver det lagt i billede-mappen og et redigeret billede (du kan selv bestemme størrelse osv.) bliver lagt i tumb. Index.php viser så de redigerede billeder, og så kan man klikke sig ind og se det originale.

<?

chdir(".");
if ($dir = dir("."))
{
$dir -> rewind();

while ($file = $dir->read())
{
if($file == "." || $file == ".." || $file == "index.php" || $file == "tumb")
{
continue;
}

if(is_dir($file))
{
echo "<BR><A HREF=\"$file\">$file</A>\n";
}
else $files[] = $file;
}

$dir -> close;

echo "";
for ($i=0; $i<count($files); $i++)
{
echo "<a href=\"$files[$i]\"> <IMG src=\"tumb/$files[$i]\" style=\"border-color: 000000; border-width: 1\" alt=\"$files[$i]\"></A>\n";
}
}
else echo("couldn't open dir");
?>

<?

    /*
        Class    : imageresize
        Purpose  : Re- size/sample an image (JPG or PNG)

        Variables :
                    new_width        - New width
                    new_height        - New height
                    resize_ax        - If 1 = auto. adjust is done to height, 2 = .. to width.
                    maintain_aspect    - If true, image resizing will maintain aspect ratio of image.
                                      If true, only new_width or new_height should be set.
                                      Whichever is set last is effective.

                    output            - Output filename. If emtpy "" output will be to stdout.
                    jpeg_quality    - Quality of JPEG image

        Functions :
                    bool source(string image_file)
                        Loads image_file as the active source image

                    bool resize()
                        Performs a pixel resize on the source image

                    bool resample()
                        Performs a resample on the source image


            All returns true on success, otherwise false.
    */
    class imageresize {
        var $new_width;            # Positive value: width in px; Negative: width in % of org. width
        var $new_height;        # Same as above for height.
        var $resize_ax;            # 1 = Resize width proportionally to width; 2 = Resize height ...
                                # if maintain_aspect is true.
                                # Default: 1

        var $maintain_aspect;    # Maintain aspect ratio. True/False.
                                # Default: True

        var $output;            # Filename to output to. If emtpy, outputs image directly to the browser.
                                # $output is reset after a call to set_source();

        var $jpeg_quality;        # Quality of JPEG output (0 - 100).
                                # Default: 90

        var $org_width;            # If set_source() was called, and succeeded, returns the original width.
        var $org_height;        # Same as above for height

        # internal variables, not to be altered!
        var $i_image;
        var $i_src;
        var $i_isGD2;

        # Main function
        function imageresize() {
            # Initialize variables with default values
            $this->maintain_aspect = 1;
            $this->jpeg_quality = 90;
            $this->resize_ax = 1;

            $this->new_height = 0;
            $this->new_width = 0;

            $this->org_height = 0;
            $this->org_width = 0;

            $this->i_src = 0;
            $this->i_isGD2 = true;
        }

        # Returns true/false depending on success.
        function source($image_file) {
            # if file does not exist, return false
            if (!file_exists($image_file)) return false;
            # set image as active image
            $this->i_image = $image_file;

            # load the image set in i_image, and assign image resource to i_src.
            if ($this->int_loadimage()) {
                $this->org_width = imagesx($this->i_src);
                $this->org_height = imagesy($this->i_src);
                $this->output = "";

                return true;
            } else {
                # clear image on load failure
                $this->i_image = "";
                return false;
            }
        }

        # Resample loaded image. (requires GD 2.0.1 or later)
        function resample() {
            if (!$this->i_image) return false;

            # get the resource to the destination image
            if ($dest = $this->int_get_destimage()) {
                # copy the image from i_src and resample it, then place it on $dest.
                imagecopyresampled($dest, $this->i_src, 0, 0, 0, 0, $this->new_width, $this->new_height, $this->org_width, $this->org_height);
                # output the image
                $this->int_outputimage($dest);

                return true;
            } else {
                return false;
            }
        }

        # Pixel reesize loaded image. (requires GD 2.0.1 or later)
        function resize() {
            if (!$this->i_image) return false;

            # get the resource to the destination image
            if ($dest = $this->int_get_destimage()) {
                # copy the image from i_src and resize it, then place it on $dest.
                imagecopyresized($dest, $this->i_src, 0, 0, 0, 0, $this->new_width, $this->new_height, $this->org_width, $this->org_height);
                # output the image
                $this->int_outputimage($dest);

                return true;
            } else {
                return false;
            }
        }

        # Returns image resource on succes, otherwise false.
        function int_loadimage() {
            if (!$this->i_image) return false;
            # determine file type and load image
            switch ($this->int_imagetype()) {
                case ".jpg": $this->i_src = @imagecreatefromjpeg($this->i_image); break;
                case ".png": $this->i_src = @imagecreatefrompng($this->i_image); break;
                case ".bmp": $this->i_src = @imagecreatefromwbmp($this->i_image); break;
            }

            return $this->i_src;
        }

        # Returns file extension of loaded image
        function int_imagetype() {
            if (!$this->i_image) return false;
            return strtolower(strrchr($this->i_image, "."));
        }

        # Returns image resource to destination image on success, otherwise false.
        function int_get_destimage() {
            if ($this->maintain_aspect) {
                if ($this->new_width > 0 || $this->new_height > 0) {
                    if ($this->resize_ax == 1) {
                        $ratio = ($this->new_width * 100) / $this->org_width;
                        $this->new_height =  floor($this->org_height * ($ratio / 100));
                    } else if ($this->resize_ax == 2) {
                        $ratio = ($this->new_height * 100) / $this->org_height;
                        $this->new_width =  floor($this->org_width * ($ratio / 100));
                    }
                } else if ($this->new_width < 0 || $this->new_height < 0) {
                    if ($this->new_width < 0) {
                        $width = abs($this->new_width) / 100;
                        $this->new_width = $this->org_width * $width;
                        $this->new_height = $this->org_height * $width;
                    }
                    if ($this->new_height < 0) {
                        $height = abs($this->new_height) / 100;
                        $this->new_height = $this->org_height * $height;
                        $this->new_width = $this->org_width * $height;
                    }
                }
            } else {
                if ($this->new_width < 0) $this->new_width = $this->org_width * (abs($this->new_width) / 100);
                if ($this->new_height < 0) $this->new_height = $this->org_height * (abs($this->new_height) / 100);
            }

            $dest = (!$this->i_isGD2) ? @imagecreate($this->new_width, $this->new_height):@imagecreatetruecolor($this->new_width, $this->new_height);
            return $dest;
        }

        # Outputs image from $dest
        function int_outputimage($dest) {
            # array with Content-Type's
            $mimes = array(".jpg" => "image/jpeg", ".png" => "image/png");
            # if image should be send directly to stdout, then send the appropriate header
            if (!$this->output) header("Content-Type: " . $mimes[$this->int_imagetype()]);

            # output the image
            switch ($this->int_imagetype()) {
                case ".jpg": ($this->output) ? imagejpeg($dest, $this->output, $this->jpeg_quality):imagejpeg($dest, "", $this->jpeg_quality); break;
                case ".png": ($this->output) ? imagepng($dest, $this->output):imagepng($dest); break;
            }

            # clear up resources
            imagedestroy($dest);
        }
    }

    /*
        Class    : imagethumbnail; extends imageresize
        Purpose  : Generate thumbnails of pictures and save thumnail for later and faster retreival.

        Functions :
                    get_thumbnail(string image, int width, int height[, bool resize_type = 0 [, bool regenerate = false]])
                        Get the filename of a thumbnail og "image".
                        Either width or height must be set, but not both. One *has* to be zero.
                        Whichever is set will have its opposite proportionally adjusted.
                        i.e.: if width = 100, the thumbnail will be 100 px wide and n px high (adjusted)

                        If resize_type is 0, pixel resizing will be used, if 1 resampling will be used.
                        If regenerate is true the thumbnail will be generated even if it already exists.

                        Returns: filename of thumbnail on success, otherwise false.
    */
    class imagethumbnail extends imageresize {
        function get_thumbnail($image, $width, $height, $resize_type = 0, $regenerate = false) {
            if (!file_exists($image) || ($width > 0 && $height > 0)) return false;

            # make thumbnail filename
            $thumbnail_file = dirname($image) . "/tmb_" . basename($image);

            # if thumbnail does not exists or regenerate is true, then generate the thumbnail
            if (!@file_exists($thumbnail_file) || $regenerate) {
                # load image
                $this->source($image);
                # set output filename
                $this->output = $thumbnail_file;
                if ($width > 0) {
                    $this->new_width = $width;
                } else {
                    $this->new_height = $height;
                }

                # re -size/-sample image and save the image
                ($resize_type == 1) ? $this->resample():$this->resize();
            }

            # return the filename
            return $thumbnail_file;
        }
    }

if ($action)
{
if (isset($_FILES['upfile']))
{
    $str1 = $_FILES['upfile']['name'];
    $str2 = $_FILES['upfile']['size'];
    $str3 = $_FILES['upfile']['type'];
    $navn = md5("$sessionid$session_user$session_pass". time());
    $filetyper = array("image/jpeg", "image/pjpeg", "image/png", "image/x-png");
    $dist = "/web/DIN ADRESSE/";
    if (isset($_FILES['upfile']['name']) && $_FILES['upfile']['name'] == "")
    {
    $alert = "Du skal vælge en fil til uploade.";
    }
    elseif (!in_array($_FILES['upfile']['type'], $filetyper))
    {
        $alert = "Typen du prøver at uploade er ikke tilladt.";
    }
        if (isset($_FILES['upfile']['name']) && $_FILES['upfile']['name'] !="")
        {
            if(is_uploaded_file($_FILES['upfile']['tmp_name']))
            {
                if (move_uploaded_file($_FILES['upfile']['tmp_name'], $dist . $_FILES['upfile']['name']))
                {
                    $rz = new imageresize();
                    $rz->source("$str1");
                    $rz->new_width = 170;
                    $rz->jpeg_quality = 90;
          $rz->output = "tumb/$str1";
                    $rz->resample();
                    $alert = "Du har nu uploadet et billede..";
                }
                else
                {
                    $alert = "Filen blev ikke flyttet!";
                }
            }
            else
            {
                $alert = "Der opstod en fejl ved upload.";
            }
                $alert = "Du har uploadet dit billede kaldet";
        }
    }
    else
    {
        $alert = "Du skal vælge en fil til upload.";
    }
}
?>


<center><br><br>Upload et billede til mappen:<br><br>

<table><tr>
<td>
<center><form action="<? echo "$PHP_SELF"; ?>" method="post" enctype="multipart/form-data" name="form1">
  <br><? echo "$alert <b>$str1</b>"; ?><br>
  <input name="upfile" type="file" id="upfile" class="inputfield" style='font-family: verdana; font-size: 8pt; background-color=#E3E3E3; border: 1px solid #000000'>
  <br><br>
  <input name="submit" type="submit" value="Send" style='font-family: verdana; font-size: 8pt; background-color=#E3E3E3; border: 1px solid #000000'>
  <input name="action" type="hidden" id="action" value="true">
</form></center></td>

</tr></table>
</center>





------------------------
if($file == "." || $file == ".." || $file == "index.php" || $file == "tumb")
angivere hvilke filer der skal skjules på index.php

echo "<a href=\"$files[$i]\"> <IMG src=\"tumb/$files[$i]\" style=\"border-color: 000000; border-width: 1\" alt=\"$files[$i]\"></A>\n";
er scriptet der viser det redigerede billede som kan klikkes større.

$dist = "/web/DIN ADRESSE/billeder";
Her skriver du stien til dit webhotel. Hvis du ikke kender den, står den sikkert på din udbyders hjemmeside.

$rz->new_width = 170;
Angiver bredden på det nye billede.

$rz->jpeg_quality = 90;
Angiver kvaliteten på det nye billede.


Bemærk, scriptet kan kun bruges til at uploade JPG og PNG filer, men gif filer kan jo bare indkodes.
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Vi tilbyder markedets bedste kurser inden for webudvikling

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester