Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

André Ricardo Theodoro

Problemas com sistema de fotos

Recommended Posts

Bom dia pessoal!

 

Estou com um problema no meu sistema de fotos.

A parte de fazer upload e de gravar os dados no

bd está ok, o problema é que criei uma função

para dimensionar a imagem, que deve ser 500X375

e a função não está funcionando, parece que os dados não

são passados pela função, ou sei lá o q!

Já tentei várias coisas mas nada resolve!

:huh:

Será q alguém consegue me ajudar!?

 

Este é o código:

PHP
<?php require_once('conecta.php'); ?>

<?php

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")  

{

  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

 

  switch ($theType) {

    case "text":

      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

      break;    

    case "long":

    case "int":

      $theValue = ($theValue != "") ? intval($theValue) : "NULL";

      break;

    case "double":

      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";

      break;

    case "date":

      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

      break;

    case "defined":

      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;

      break;

  }

  return $theValue;

}

 

$editFormAction = $_SERVER['PHP_SELF'];

if (isset($_SERVER['QUERY_STRING'])) {

  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);

}  

 

// Aqui, pegamos o nome e o nome temporário da imagem enviada.

$foto = $_FILES["foto_foto"]["name"];

$fotoTmp = $_FILES["foto_foto"]["tmp_name"];

$fotoSize = $_FILES["foto_foto"]["size"];

$fotoTipo = $_FILES["foto_foto"]["type"];

 

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {

 if($fotoSize >= "51200"){

   $erro =  ("Arquivo é maior que o permitido.");

}

 if($erro != ""){

  echo "$erro";

  }

  else{

// Acrescentamos o campo: foto_data.

// Em VALUES, alteramos o primeiro %s por '$foto'; e acrescentamos o comando NOW().

mysql_select_db($database);

    $query_rsUltimaFoto = "SELECT *, date_format(foto_data, '%d/%m/%Y') AS foto_data FROM w_floricultura ORDER BY foto_id DESC";

    $rsUltimaFoto = mysql_query($query_rsUltimaFoto) or die(mysql_error());

    $row_rsUltimaFoto = mysql_fetch_assoc($rsUltimaFoto);

    $totalRows_rsUltimaFoto = mysql_num_rows($rsUltimaFoto);

    $fotoRequisitada = $row_rsUltimaFoto['foto_id'];

        $foto = $row_rsUltimaFoto['foto_id']+1;

$insertSQL = sprintf("INSERT INTO w_floricultura (foto_foto, foto_titulo, foto_valor, foto_legenda, foto_data) VALUES ('$foto', %s, %s, %s, NOW())",

                                           GetSQLValueString($_POST['foto_titulo'], "text"),

                                           GetSQLValueString($_POST['foto_valor'], "text"),

                       GetSQLValueString($_POST['foto_legenda'], "text"));

 

//

function reduz_imagem_jpg($img, $max_x, $max_y, $imgNome) {

       

        //pega o tamanho da imagem ($original_x, $original_y)

        list($width, $height) = getimagesize($img);

       

        $original_x = $width;

        $original_y = $height;

       

        // se a largura for maior que altura

        if($original_x > $original_y) {

            $porcentagem = (100 * $max_x) / $original_x;

            } else {

                $porcentagem = (100 * $max_y) / $original_y;

        }

       

        $tamanho_x = $original_x * ($porcentagem / 100);

        $tamanho_y = $original_y * ($porcentagem / 100);

        $dimensao = $_POST["dimensao"];

        if ($dimensao=='H'){

           $tamanho_x= 500;

           $tamanho_y= 375;

        }elseif ($dimensao=='V'){

           $tamanho_y= 500;

           $tamanho_x= 375;}

        $image_p = imagecreatetruecolor($tamanho_x, $tamanho_y);

        $image   = imagecreatefromjpeg($img);

       

        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $tamanho_x, $tamanho_y, $width, $height);

        return imagejpeg($image_p, $imgNome, 100);

    }

 

//

$pasta = "fotos"; //Nome da pasta para onde vão os arquivos

if (copy($fotoTmp,"$pasta/".$foto)){

echo("<font face=verdana size=1><b>Arquivo enviado com sucesso!</b></font>");

}else{

echo ("<font face=verdana size=1><b>Erro no envio do arquivo!</b></font>");

}

  mysql_select_db($database);

  $Result1 = mysql_query($insertSQL) or die(mysql_error());

}

    $insertGoTo = "index.php";

    if (isset($_SERVER['QUERY_STRING'])) {

      $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";

      $insertGoTo .= $_SERVER['QUERY_STRING'];

  }

  header(sprintf("Location: %s", $insertGoTo));

}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Postar foto</title>

</head>

 

<body>

 

<h1>Postagem de fotos</h1>

 

<html>

<body>

<form action="<?php echo $editFormAction; ?>" method="post" enctype="multipart/form-data" name="form1">

<table align="center">

          <tr valign="baseline">

            <td width="106" align="right" nowrap>Foto:</td>

            <td width="375"><input name="foto_foto" type="file" size="32" />

          </tr>

          <tr valign="baseline">

            <td nowrap align="right">Nome:</td>

            <td><input type="text" name="foto_titulo" value="" size="32" /></td>

          </tr>

                  <tr valign="baseline">

            <td nowrap align="right">Valor:</td>

            <td><input type="text" name="foto_valor" value="" size="32" /></td>

          </tr>

          <tr valign="baseline">

            <td nowrap align="right" valign="top">Descrição:</td>

            <td><textarea name="foto_legenda" cols="50" rows="5"></textarea>

            </td>

          </tr>

          <tr valign="baseline">

            <td nowrap align="right">Dimensionar foto:</td>

            <td>      <input name="dimensao" type="radio" value="V" checked="CHECKED" />

              Vertical

              <input name="dimensao" type="radio" value="H" />

        Horizontal</td></tr>

          <tr valign="baseline">

            <td height="27" align="right" nowrap> </td>

            <td><input name="submit" type="submit" value="Postar Foto" /></td>

          </tr>

                  </table>

                  <input type="hidden" name="MM_insert" value="form1">

</form>

</body>

</html>

http://forum.imasters.com.br/public/style_emoticons/default/ermm.gif

Compartilhar este post


Link para o post
Compartilhar em outros sites

qual o erro?

 

Ele não dá erro.

Como disse, anteriormente, ele grava tudo ok, tanto no diretório,

como no banco de dados, o problema é que ele não executa a

função que dimensiona ele, ou seja, eu mudo a foto para vertical

ou horizontal e nada acontece.

Ele não fica com o tamanho 500X375 e nem na vertical ou

horizontal.

 

Alguém saberia me ajudar a mecher nas propriedades da foto!?

Tipo eu copio a foto do usuário pelo upload e precisaria dimensiona-

la em 500X375 e coloca-la na horizontal ou vertical! http://forum.imasters.com.br/public/style_emoticons/default/ermm.gif

Compartilhar este post


Link para o post
Compartilhar em outros sites

Eu encontrei essa função que serve para o meu objtivo:

//pega o tamanho da imagem ($original_x, $original_y)
list($width, $height) = getimagesize($img);

$original_x = $width;
$original_y = $height;

// se a largura for maior que altura
if($original_x > $original_y) {
   $porcentagem = (100 * $max_x) / $original_x;	  
}
else {
   $porcentagem = (100 * $max_y) / $original_y;  
}

$tamanho_x = $original_x * ($porcentagem / 100);
$tamanho_y = $original_y * ($porcentagem / 100);
$dimensao = $_POST["dimensao"];
		if ($dimensao=='H'){
		   $tamanho_x= 500;
		   $tamanho_y= 375;
		}elseif ($dimensao=='V'){
		   $tamanho_y= 500;
		   $tamanho_x= 375;}
$image_p = imagecreatetruecolor($tamanho_x, $tamanho_y);
$image   = imagecreatefromjpeg($img);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $tamanho_x, $tamanho_y, $width, $height);


return imagejpeg($image_p, $nome_foto, 100);

}

Alguém sabe como implantar ele no meu sistema?

Tentei várias vezes mais sem sucesso!

 

Fico no aguardo!

Compartilhar este post


Link para o post
Compartilhar em outros sites

reduz_imagem_jpg($img, $max_x, $max_y, $imgNome)
Inserindo esta linha no seu código (não dentro da função, óbvio) e passando os parâmetros adequados. http://forum.imasters.com.br/public/style_emoticons/default/thumbsup.gif

Vo dá uma de burro agora mas.....

Não consegui passar os parâmetros.....

Tem como você me explicar melhor!?

Por favor! http://forum.imasters.com.br/public/style_emoticons/default/ermm.gif

Compartilhar este post


Link para o post
Compartilhar em outros sites

Inclua seu código ai, por favor. :)

Ok!

<?php require_once('conecta.php'); ?> 
<?php 
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")  
{ 
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue; 

  switch ($theType) { 
	case "text": 
	  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; 
	  break;	 
	case "long": 
	case "int": 
	  $theValue = ($theValue != "") ? intval($theValue) : "NULL"; 
	  break; 
	case "double": 
	  $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL"; 
	  break; 
	case "date": 
	  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; 
	  break; 
	case "defined": 
	  $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; 
	  break; 
  } 
  return $theValue; 
}

// Função que cria a imagem, não trabalharemos com upload. 
function reduz_imagem_jpg($img, $max_x, $max_y, $foto) {

//pega o tamanho da imagem ($original_x, $original_y)
list($width, $height) = getimagesize($img);

$original_x = $width;
$original_y = $height;

// se a largura for maior que altura
if($original_x > $original_y) {
   $porcentagem = (100 * $max_x) / $original_x;	  
}
else {
   $porcentagem = (100 * $max_y) / $original_y;  
}

$tamanho_x = $original_x * ($porcentagem / 100);
$tamanho_y = $original_y * ($porcentagem / 100);
$dimensao = $_POST["dimensao"];
		if ($dimensao=='H'){
		   $tamanho_x= 500;
		   $tamanho_y= 375;
		}elseif ($dimensao=='V'){
		   $tamanho_y= 500;
		   $tamanho_x= 375;} 	
$image_p = imagecreatetruecolor($tamanho_x, $tamanho_y);
$image   = imagecreatefromjpeg($img);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $tamanho_x, $tamanho_y, $width, $height);


return imagejpeg($image_p, $foto, 100);

}

$editFormAction = $_SERVER['PHP_SELF']; 
if (isset($_SERVER['QUERY_STRING'])) { 
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); 
}  

// Aqui, pegamos o nome e o nome temporário da imagem enviada. 
$foto = $_FILES["foto_foto"]["name"]; 
$fotoTmp = $_FILES["foto_foto"]["tmp_name"];
$fotoSize = $_FILES["foto_foto"]["size"];
$fotoTipo = $_FILES["foto_foto"]["type"];

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
 if($fotoSize >= "51200"){
   $erro =  ("WARNING: Arquivo é maior que o permitido!");
}
 if($erro != ""){
  echo "$erro";
  }
  else{
// Acrescentamos o campo: foto_data. 
// Em VALUES, alteramos o primeiro %s por '$foto'; e acrescentamos o comando NOW().
mysql_select_db($database); 
	$query_rsUltimaFoto = "SELECT *, date_format(foto_data, '%d/%m/%Y') AS foto_data FROM w_floricultura ORDER BY foto_id DESC"; 
	$rsUltimaFoto = mysql_query($query_rsUltimaFoto) or die(mysql_error()); 
	$row_rsUltimaFoto = mysql_fetch_assoc($rsUltimaFoto); 
	$totalRows_rsUltimaFoto = mysql_num_rows($rsUltimaFoto); 
	$fotoRequisitada = $row_rsUltimaFoto['foto_id'];
	$foto = $row_rsUltimaFoto['foto_id']+1;
$insertSQL = sprintf("INSERT INTO w_floricultura (foto_foto, foto_titulo, foto_valor, foto_legenda, foto_data) VALUES ('$foto', %s, %s, %s, NOW())", 
					   GetSQLValueString($_POST['foto_titulo'], "text"),
					   GetSQLValueString($_POST['foto_valor'], "text"), 
					   GetSQLValueString($_POST['foto_legenda'], "text"));
					   
$dimensiona = reduz_imagem_jpg($img, $max_x, $max_y, $foto);

$pasta = "fotos"; //Nome da pasta para onde vão os arquivos
if (copy($fotoTmp, "$pasta/".$foto)){
echo("<font face=verdana size=1><b>Arquivo enviado com sucesso!</b></font>");
}else{
echo ("<font face=verdana size=1><b>Erro no envio do arquivo!</b></font>");
}
  mysql_select_db($database); 
  $Result1 = mysql_query($insertSQL) or die(mysql_error());
}
	$insertGoTo = "index.php"; 
	if (isset($_SERVER['QUERY_STRING'])) { 
	  $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?"; 
	  $insertGoTo .= $_SERVER['QUERY_STRING']; 
  } 
  header(sprintf("Location: %s", $insertGoTo));
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
<title>Postar foto</title> 
</head> 

<body> 

<h1>Postagem de fotos</h1>
 
<html>
<body>
<form action="<?php echo $editFormAction; ?>" method="post" enctype="multipart/form-data" name="form1">
<table align="center">
		  <tr valign="baseline">
			<td width="106" align="right" nowrap>Foto:</td>
			<td width="375"><input name="foto_foto" type="file" size="32" />
		  </tr>
		  <tr valign="baseline">
			<td nowrap align="right">Nome:</td>
			<td><input type="text" name="foto_titulo" value="" size="32" /></td>
		  </tr>
		  <tr valign="baseline">
			<td nowrap align="right">Valor:</td>
			<td><input type="text" name="foto_valor" value="" size="32" /></td>
		  </tr>
		  <tr valign="baseline">
			<td nowrap align="right" valign="top">Descrição:</td>
			<td><textarea name="foto_legenda" cols="50" rows="5"></textarea>
			</td>
		  </tr>
		  <tr valign="baseline">
			<td nowrap align="right">Dimensionar foto:</td>
			<td>	  <input name="dimensao" type="radio" value="V" checked="CHECKED" />
			  Vertical 
				<input name="dimensao" type="radio" value="H" />
			  Horizontal</td></tr>
		  <tr valign="baseline">
			<td height="27" align="right" nowrap> </td>
			<td><input name="submit" type="submit" value="Postar Foto" /></td>
		  </tr>
		  </table>
		  <input type="hidden" name="MM_insert" value="form1">
</form>
</body>
</htm>

:huh:

Compartilhar este post


Link para o post
Compartilhar em outros sites

Como eu disse em minha primeira resposta, você precisa informar os parâmetros adequadamente, desse jeito você simplesmente copiou e colou o cabeçalho da função.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olha só......

 

Agora tá funcionando, mas a imagem, aparece toda preta....

A função está criando uma imagem no formato q eu quero q

é 500X375 e colocando na vertical e horizontal.....

mas não a imagem do upload, porq no lugar fica uma imagem

toda preta........ :huh:

Compartilhar este post


Link para o post
Compartilhar em outros sites

$img -> É o endereço da imagem original

$max_x -> Largura máxima da thumb a ser gerada

$max_y -> Altura máxima da thumb a ser gerada

$imgNome -> Endereço para salvar a imagem reduzida

Compartilhar este post


Link para o post
Compartilhar em outros sites

Pessoal, já tentei d todas as formas

tentar fazer essa função funcionar,

mas nada da certo......

 

Olha como ta o código:

function reduz_imagem_jpg($img, $max_x, $max_y, $imgNome) {
		$imgNome = $_FILES["foto_foto"]["name"]; 
		$img = $_FILES["foto_foto"]["tmp_name"];
		//pega o tamanho da imagem ($original_x, $original_y)
		list($width, $height) = getimagesize($img);
		
		$original_x = $width;
		$original_y = $height;
		
		// se a largura for maior que altura
		if($original_x > $original_y) {
			$porcentagem = (100 * $max_x) / $original_x;
			} else {
				$porcentagem = (100 * $max_y) / $original_y;
		}
		
		$tamanho_x = $original_x * ($porcentagem / 100);
		$tamanho_y = $original_y * ($porcentagem / 100);
		$dimensao = $_POST["dimensao"];
		if ($dimensao=='H'){
		   $tamanho_x= 500;
		   $tamanho_y= 375;
		}elseif ($dimensao=='V'){
		   $tamanho_y= 500;
		   $tamanho_x= 375;}
		
		$image_p = imagecreatetruecolor($tamanho_x, $tamanho_y);
		$image   = imagecreatefromjpeg($img);
		
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $tamanho_x, $tamanho_y, $width, $height);
		return imagejpeg($image_p, $imgNome, 100);
		 
	}
	   
	$pasta = "fotos"; //Nome da pasta para onde vão os arquivos
	reduz_imagem_jpg();
	if (copy($fotoTmp, "$pasta/".$foto)){
		   echo("<font face=verdana size=1><b>Arquivo enviado com sucesso!</b></font>");
	}else{
		   echo ("<font face=verdana size=1><b>Erro no envio do arquivo!</b></font>");
}

Passei os parâmetros para a função conforme o Frenesi

havia me dito!

Só não coloquei do max_x e max_y porq eles são definidos conforme

a imagem estah na vertical ou horizontal!

 

Se alguém tiver alguma dica HELP!!!!!

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.