PHP - Guardar la imágen redimensionada en BD

 
Vista:

Guardar la imágen redimensionada en BD

Publicado por aleksander (1 intervención) el 21/08/2013 14:58:25
Buenas,

Estoy realizando la subida de una imágen a la BD. Hasta aquí bien, pero hago un redimensionado de esta y lo hace bien porque si lo muestro en la web se ve redimensionada. Pero a la hora de guardarlo en la BD solo me guarda la imágen original y me da error al guardar la redimensionada.

Para ello estoy utilizando "process.php" que es el fichero que recibe los datos y la imágen y realiza la query y "SimpleImage.php" que he encontrado en varios sitios que hace el redimensionado.

Alguien me puede dar pistas de por qué es? Creo que debería de recoger el objeto imagen pero no soy capaz de hacerlo, solo lo muestra.

Gracias de ante mano.

process.php

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<?php
    require_once('globals.php');
 
    function assertValidUpload($code)
    {
        if ($code == UPLOAD_ERR_OK) {
            return;
        }
 
        switch ($code) {
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                $msg = 'La imagen es demasiado larga';
                break;
 
            case UPLOAD_ERR_PARTIAL:
                $msg = 'La imagen se ha subido parcialmente';
                break;
 
            case UPLOAD_ERR_NO_FILE:
                $msg = 'No hay ninguna imagen para subir';
                break;
 
            case UPLOAD_ERR_NO_TMP_DIR:
                $msg = 'No se ha encontrado la carpeta para subir el Archivo';
                break;
 
            case UPLOAD_ERR_CANT_WRITE:
                $msg = 'No se ha podido escribir el Archivo subido';
                break;
 
            case UPLOAD_ERR_EXTENSION:
                $msg = 'Archivo que intentas subir no tiene la extension correcta';
                break;
 
            default:
                $msg = 'Error desconocido o no controlado';
        }
 
        throw new Exception($msg);
    }
 
    $errors = array();
 
    try {
        if (!array_key_exists('image', $_FILES)) {
            throw new Exception('Imagen no encontrada en los datos subidos');
        }
 
        $image = $_FILES['image'];
 
		$titulo = $_POST['titulo'];
		$nombre = $_POST['nombre'];
		$categoria = $_POST['categoria'];
		$descripcion = $_POST['descripcion'];
 
		header('Content-Type: image/jpeg');
		include("SimpleImage.php");
		$thumbImage = new SimpleImage();
		$thumbImage->load($_FILES['image']['tmp_name']);
		$thumbImage->resize(100,100);
		$thumbImage->output();
 
 
 
 
        // ensure the file was successfully uploaded
        assertValidUpload($image['error']);
 
        if (!is_uploaded_file($image['tmp_name'])) {
            throw new Exception('El archivo no es el archivo cargado');
        }
 
        $info = getImageSize($image['tmp_name']);
 
        if (!$info) {
            throw new Exception('El archivo no es una imagen');
        }
    }
    catch (Exception $ex) {
        $errors[] = $ex->getMessage();
    }
 
    if (count($errors) == 0) {
        // no errors, so insert the image
 
        $query = sprintf(
            "insert into fotos (titulo,nombre,categoria,descripcion,filename, mime_type, file_size, file_data,thumbname,thumbfile_data)
                values ('%s','%s','%s','%s', '%s', '%s', %d, '%s', %d, '%s')",
			mysql_real_escape_string($titulo),
			mysql_real_escape_string($nombre),
			mysql_real_escape_string($categoria),
			mysql_real_escape_string($descripcion),
            mysql_real_escape_string($image['name']),
            mysql_real_escape_string($info['mime']),
            $image['size'],
            mysql_real_escape_string(
				file_get_contents($image['tmp_name'])
			),
			mysql_real_escape_string($thumbImage ['name']),
            mysql_real_escape_string(
				file_get_contents($thumbImage ['tmp_name'])
			)
        );
 
        mysql_query($query, $db);
 
        $id = (int) mysql_insert_id($db);
 
        // finally, redirect the user to view the new image
        //header('Location: view.php?id=' . $id);
		echo "<p>La foto ha sido subida correctamente</p>";
		echo "<a href='upload.php'>Volver</a>";
        exit;
    }
?>
<html>
    <head>
        <title>Error</title>
    </head>
    <body>
        <div>
            <p>Han ocurrido los siguientes errores:</p>
 
            <ul>
                <?php foreach ($errors as $error) { ?>
                    <li>
                        <?php echo htmlSpecialChars($error) ?>
                    </li>
                <?php } ?>
            </ul>
 
            <p>
                <a href="upload.php">Volver</a>
				* vuelve a la pagina para subir la foto
            </p>
        </div>
    </body>
</html>


SimpleImage.php

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
 
class SimpleImage {
 
   var $image;
   var $image_type;
 
   function load($filename) {
 
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
			$this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
			$this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
			$this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image,$filename);
      }
      if( $permissions != null) {
 
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
          imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {
          imagepng($this->image);
      }
   }
   function getWidth() {
 
      return imagesx($this->image);
   }
   function getHeight() {
 
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
 
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
 
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
 
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
 
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }
 
}
?>
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de terra

Guardar la imágen redimensionada en BD

Publicado por terra (62 intervenciones) el 22/08/2013 20:06:54
Hola!

1
"insert into fotos (titulo,nombre,categoria,descripcion,filename, mime_type, file_size, file_data,thumbname,thumbfile_data) values ('%s','%s','%s','%s', '%s', '%s', %d, '%s', %d, '%s')"


Observando la consulta he notado que el valor NOVENO lo tienes coo %d en vez de '%s' .
No utilizo mucho este tipo de consulta pero lo digo por ayudar.


Saludos!!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar