PHP - Error imagedestroy

 
Vista:

Error imagedestroy

Publicado por Ruben (3 intervenciones) el 10/12/2022 10:42:11
Hola amigos,
Estuve buscando una funcion para redimensionar y cortar automaticamente mis imagenes. Encontre el siguiente codigo, parece funcionar bien pero me salta un error que me esta volviendo loco. No logro resolver

Error
1
Warning: imagedestroy(): supplied resource is not a valid Image resource in

Function

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
<?php
function resize_image($method,$image_loc,$new_loc,$width,$height) {
	if (!array_key_exists('errors', $GLOBALS) || !is_array($GLOBALS['errors'])) { $GLOBALS['errors'] = array(); }
 
	if (!in_array($method, array('force','max','crop'))) { $GLOBALS['errors'][] = 'Invalid method selected.'; }
 
	if (!$image_loc) { $GLOBALS['errors'][] = 'No source image location specified.'; }
	else {
	if ((substr(strtolower($image_loc),0,7) == 'http://') || (substr(strtolower($image_loc),0,7) == 'https://')) { } // don't check to see if file exists since it's not local
		elseif (!file_exists($image_loc)) { $GLOBALS['errors'][] = 'Image source file does not exist.'; }
		$extension = strtolower(substr($image_loc,strrpos($image_loc,'.')));
		if (!in_array($extension,array('.jpg','.jpeg','.png','.gif','.bmp'))) { $GLOBALS['errors'][] = 'Invalid source file extension!'; }
	}
 
	if (!$new_loc) { $GLOBALS['errors'][] = 'No destination image location specified.'; }
	else {
		$new_extension = strtolower(substr($new_loc,strrpos($new_loc,'.')));
		if (!in_array($new_extension,array('.jpg','.jpeg','.png','.gif','.bmp'))) { $GLOBALS['errors'][] = 'Invalid destination file extension!'; }
	}
 
	$width = abs(intval($width));
	if (!$width) { $GLOBALS['errors'][] = 'No width specified!'; }
 
	$height = abs(intval($height));
	if (!$height) { $GLOBALS['errors'][] = 'No height specified!'; }
 
	if (count($GLOBALS['errors']) > 0) { echo_errors(); return false; }
 
	if (in_array($extension,array('.jpg','.jpeg'))) { $image = @imagecreatefromjpeg($image_loc); }
	elseif ($extension == '.png') { $image = @imagecreatefrompng($image_loc); }
	elseif ($extension == '.gif') { $image = @imagecreatefromgif($image_loc); }
	elseif ($extension == '.bmp') { $image = @imagecreatefromwbmp($image_loc); }
 
	if (!$image) { $GLOBALS['errors'][] = 'Image could not be generated!'; }
	else {
		$current_width = imagesx($image);
		$current_height = imagesy($image);
		if ((!$current_width) || (!$current_height)) { $GLOBALS['errors'][] = 'Generated image has invalid dimensions!'; }
	}
	if (count($GLOBALS['errors']) > 0) { @imagedestroy($image); echo_errors(); return false; }
 
	if ($method == 'force') { $new_image = resize_image_force($image,$width,$height); }
	elseif ($method == 'max') { $new_image = resize_image_max($image,$width,$height); }
	elseif ($method == 'crop') { $new_image = resize_image_crop($image,$width,$height); }
 
	if ((!$new_image) && (count($GLOBALS['errors'] == 0))) { $GLOBALS['errors'][] = 'New image could not be generated!'; }
	if (count($GLOBALS['errors']) > 0) { @imagedestroy($image); echo_errors(); return false; }
 
	$save_error = false;
	if (in_array($extension,array('.jpg','.jpeg'))) { imagejpeg($new_image,$new_loc) or ($save_error = true); }
	elseif ($extension == '.png') { imagepng($new_image,$new_loc) or ($save_error = true); }
	elseif ($extension == '.gif') { imagegif($new_image,$new_loc) or ($save_error = true); }
	elseif ($extension == '.bmp') { imagewbmp($new_image,$new_loc) or ($save_error = true); }
	if ($save_error) { $GLOBALS['errors'][] = 'New image could not be saved!'; }
	if (count($GLOBALS['errors']) > 0) { @imagedestroy($image); @imagedestroy($new_image); echo_errors(); return false; }
 
	imagedestroy($image);
	imagedestroy($new_image);
 
	return true;
}
 
function echo_errors() {
	if ((!array_key_exists('errors',$GLOBALS)) || (!is_array($GLOBALS['errors']))) { $GLOBALS['errors'] = array(); }
	foreach ($GLOBALS['errors'] as $error) { echo '<p style="color:red;font-weight:bold;">Error: '.$error.'</p>'; }
}
 
 
function resize_image_crop($image, $width, $height) {
	if (!array_key_exists('errors', $GLOBALS) || !is_array($GLOBALS['errors'])) { $GLOBALS['errors'] = array(); }
	$w = @imagesx($image); // current width
	$h = @imagesy($image); // current height
	if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image could not be resized because it was not a valid image.'; return false; }
	if (($w == round($width)) && ($h == round($height))) { return $image; } // no resizing needed
 
	// try max width first...
	$ratio = $width / $w;
	$new_w = $width;
	$new_h = $h * $ratio;
 
	// if that created an image smaller than what we wanted, try the other way
	if ($new_h < $height) {
		$ratio = $height / $h;
		$new_h = $height;
		$new_w = $w * $ratio;
	}
 
	// resize the image
	$new_w = round($new_w);
	$new_h = round($new_h);
	$image2 = imagecreatetruecolor($new_w, $new_h);
	imagecopyresampled($image2, $image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
 
	// check to see if cropping needs to happen
	if (($new_h != $height) || ($new_w != $width)) {
		$image3 = imagecreatetruecolor($width, $height);
		if ($new_h > $height) { //crop vertically
			$extra = $new_h - $height;
			$x = 0; // source x
			$y = round($extra / 2); // source y
			imagecopyresampled($image3, $image2, 0, 0, $x, $y, $width, $height, $width, $height);
		}
		else {
			$extra = $new_w - $width;
			$x = round($extra / 2); // source x
			$y = 0; // source y
			imagecopyresampled($image3, $image2, 0, 0, $x, $y, $width, $height, $width, $height);
		}
		imagedestroy($image2);
		return $image3;
	}
	else {
		return $image2;
	}
}
?>



Muchas gracias a todos
un saludo
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

Error imagedestroy

Publicado por Ruben (3 intervenciones) el 10/12/2022 12:34:58
He encontrado (creo) el problema.

Cuando la imagen no necesita ser redimensionada, te lleva a esta linea.

1
if (($w == round($width)) && ($h == round($height))) { return $image; }

el return te lleva aqui:
1
$new_image = resize_image_crop($image,$width,$height);

y luego a:
1
imagedestroy($new_image);

Puede ser pongo no llega el width o el height?
Alguna idea de como solucionarlo?
saludos
gracias
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
Imágen de perfil de Kathyu
Val: 1.802
Plata
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Error imagedestroy

Publicado por Kathyu (905 intervenciones) el 11/12/2022 10:41:38
No he analizado a profundidad pero si ya tiene la base de donde se genera el error es de poner una condición antes de que se ejecute esa línea para que no le de el error.

Ahora, como determina que una imagen no necesita ser redimensionada?? creo que por acá andaría la base de su condicional...
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

Error imagedestroy

Publicado por Ruben (3 intervenciones) el 11/12/2022 12:52:04
Hola Kathyu
gracias por tu respuesta.

No redimensiona la imagen pero si crea una nueva más comprimida.

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
Imágen de perfil de Kathyu
Val: 1.802
Plata
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Error imagedestroy

Publicado por Kathyu (905 intervenciones) el 12/12/2022 14:48:43
Entonces el width y height siguen siendo iguales, esa podría ser una opción a evaluar.
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