sql >> Base de Datos >  >> RDS >> Mysql

Cambio de tamaño de imagen PHP

Que yo sepa, no puede cambiar el tamaño de la imagen antes subiéndolo (¡Podría estar equivocado!) Sin embargo, cuando subes la imagen, ésta va a un archivo temporal. Puede cambiar el tamaño de la imagen temporal y copiar la imagen redimensionada a su destino final.

Este código fue adaptado de un fragmento en FliquidStudios:Redimensionar imágenes en PHP con GD e Imagick .

Dado que (parece) desea mantener el ancho constante, realmente no necesita hacer muchas pruebas de proporción.

Actualización:

Debería poder usar esto simplemente en lugar de su código original. La mayor parte no ha cambiado.

<?php

// resizes an image to fit a given width in pixels.
// works with BMP, PNG, JPEG, and GIF
// $file is overwritten
function fit_image_file_to_width($file, $w, $mime = 'image/jpeg') {
    list($width, $height) = getimagesize($file);
    $newwidth = $w;
    $newheight = $w * $height / $width;

    switch ($mime) {
        case 'image/jpeg':
            $src = imagecreatefromjpeg($file);
            break;
        case 'image/png';
            $src = imagecreatefrompng($file);
            break;
        case 'image/bmp';
            $src = imagecreatefromwbmp($file);
            break;
        case 'image/gif';
            $src = imagecreatefromgif($file);
            break;
    }

    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    switch ($mime) {
        case 'image/jpeg':
            imagejpeg($dst, $file);
            break;
        case 'image/png';
            imagealphablending($dst, false);
            imagesavealpha($dst, true);
            imagepng($dst, $file);
            break;
        case 'image/bmp';
            imagewbmp($dst, $file);
            break;
        case 'image/gif';
            imagegif($dst, $file);
            break;
    }

    imagedestroy($dst);
}

// init file vars
$pic  = $_FILES['photo']['name'];
$target = 'uploads/' . basename( $_FILES['photo']['name']);
$temp_name = $_FILES['photo']['tmp_name'];
$type = $_FILES["photo"]["type"];

// Connects to your Database 
mysql_connect("hostname", "username", "password") or die(mysql_error()) ; 
mysql_select_db("database") or die(mysql_error()) ; 

// get form data
$name = mysql_real_escape_string(isset($_POST['name']) ? $_POST['name'] : 'No name');

//Writes the information to the database 
mysql_query("INSERT INTO `table` (name, photo) VALUES ('$name','$pic')") ; 

// resize the image in the tmp directorys
fit_image_file_to_width($temp_name, 200, $type);

//Writes the photo to the server
if(move_uploaded_file($temp_name, $target)) {

    //Tells you if its all ok 
    echo "The file ". basename( $_FILES['photo']['name'] ). " has been uploaded"; 

} else {

    //Gives and error if its not 
    echo "Sorry, there was a problem uploading your file."; 

}

?>