Ir para conteúdo

POWERED BY:

Arquivado

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

ScornInPC

carregar Imagem com ajax

Recommended Posts

Ola pessoal, tenho o seguinte script, porem quando carrego uma imagem, aparece uns caracteres estranho, e naum a imagem, tem que fazer alguma coisa a mais pra poder carregar sómente uma imagem?? quero fazer carregar uma imagem em um div e ela fique em cache, tenho que fazer mais alguma coisa nesse script??

 

 

segue o codigo

function openAjax() {   var Ajax;   try {	  Ajax = new XMLHttpRequest();   } catch(ee) {	  try {		 Ajax = new ActiveXObject("Msxml2.XMLHTTP");	  } catch(e) {		 try {			Ajax = new ActiveXObject("Microsoft.XMLHTTP");		 } catch(e) {			Ajax = false;		 }	  }   }   return Ajax;}function carregaAjax(image, id) {   if(document.getElementById){	  var Area  = document.getElementById(id);	  var Ajax = openAjax();	  Ajax.open("GET", image, true);	  Ajax.onreadystatechange = function() {									  if(Ajax.readyState == 4) {										 if(Ajax.status == 200) {											var res = Ajax.responseText;											Area.innerHTML = res;										 } else {											Area.innerHTML = "Erro";										 }									  }								   }	  Ajax.send(null);   }}

to chamando o codigo assim

 

<div id="div_imagem_src"></div><script>carregaAjax('fotos/fotos/1.jpg', 'div_imagem_src');</script>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Desculpem por mais um flood, achei a solução criando uma arquivo

 

<?php   $foto = $_GET['foto'];      echo '<img src="fotos/fotos/'.$foto.'.jpg" border="0">';   <BR>   ?>

agora chamo esta pagina ao invez da foto direta, porem ainda percebo que naum esta funcionando o cache

Compartilhar este post


Link para o post
Compartilhar em outros sites

bom, o meu codigo faz o seguinte: lista as imagem, quando clico em uma imagem, vai ficando escuro gradativamente, e aparece a imagem com o fundo todo preto.

 

vou postar como ele ta, mais ainda estou programando-o

 

galeria.php

<html>  <head>  </head>	<script src="ajax.js" type="text/javascript"></script>	<script>	   function sleep(millisecondi) {		  var now = new Date();		  var exitTime = now.getTime() + millisecondi;		  while(true) {			 now = new Date();			 if(now.getTime() > exitTime) return;		  }	   }	  function AbrirFoto(imagem_id, opc) {		 opc = opc + 0.03;		 var Area = document.getElementById('div_imagem');		 Area.style.display = 'block';		 if (opc >= 1) {			if(document.all) {			   this.style.filter = 'alpha(opacity=100)';			} else {			   Area.style.opacity = 1;			}			carregaAjax('foto.php?foto=' + imagem_id, 'div_imagem_src');			return;		 } else {			if(document.all) {			   this.style.filter = 'alpha(opacity=' + opc * 10 + ')';			} else {			   Area.style.opacity = opc;			}			setTimeout("AbrirFoto('" + imagem_id + "'," + opc + ")", 1);		 }	   }	</script>  <body style="background-color: #D8D8D8;"><?php   require_once('config.inc.php');   require_once('class-banco.inc.php');      $banco = new Conexao();      $total = $banco->Registros_Total() + (GALERIA_LINHA - ($banco->Registros_Total() % GALERIA_LINHA));   $sql = "SELECT * FROM fotos order by id ASC";   $resultado = mysql_query($sql);   $j = 0;   while($linha = mysql_fetch_row($resultado)) {	  $fotos[$j] = $linha[0];	  $j++;   }   printf('<center><div style="font-size:36pt;">Galeria</div><span style="font-size:12px; cursor:pointer; color:#0000FF">Enviar</span><BR><BR><BR><table border="0" width="%s"><tr>', GALERIA_TAMANHO);   $j = 0;   $tamanho = 100 / GALERIA_LINHA;   for ($i = 0; $i < $total; $i++) {	  if (($i%GALERIA_LINHA == 0) and ($i != 0)) {		 printf('</tr><tr>');	  }	  printf('<td align="center" width="' . $tamanho . '%%"> ');	  if (file_exists(GALERIA_THUMB . $fotos[$j] . '.jpg')) {		 printf('<img style="cursor:pointer; border:1px #979797 solid;" onClick="AbrirFoto(\''. $fotos[$j] . '\', 0)" src="' . str_replace("\\", "/", GALERIA_THUMB) . $fotos[$j] . '.jpg">');	  }	  $j++;	  printf('</td>');   }   printf('</tr></table></center>');?>   <div id="div_imagem" style="display:none; position:absolute; top:1px; left:1px; background-color: black; width: 100%; height:100%;				">	  <div id="div_imagem_src" align="center"></div>   </div>   </body></html>

ajax.js

function openAjax() {   var Ajax;   try {	  Ajax = new XMLHttpRequest();   } catch(ee) {	  try {		 Ajax = new ActiveXObject("Msxml2.XMLHTTP");	  } catch(e) {		 try {			Ajax = new ActiveXObject("Microsoft.XMLHTTP");		 } catch(e) {			Ajax = false;		 }	  }   }   return Ajax;}function carregaAjax(image, id) {   if(document.getElementById){	  var Area  = document.getElementById(id);	  var Ajax = openAjax();	  Ajax.open("GET", image, true);	  Ajax.onreadystatechange = function() {									  if(Ajax.readyState == 4) {										 if(Ajax.status == 200) {											var res = Ajax.responseText;											Area.innerHTML = res;										 } else {											Area.innerHTML = "Erro";										 }									  }								   }	  Ajax.send(null);   }}

foto.php

<?php   header("Content-type: text/html; charset=UTF-8");      require_once('config.inc.php');   require_once('class-banco.inc.php');      $foto = $_GET['foto'];   $sql = "SELECT * FROM fotos WHERE id = " . $foto;   $resultado = mysql_query($sql);   $linha = mysql_fetch_row($resultado);   $id = $linha[0];   $legenda = $linha[1];      echo '<BR><img src="'. GALERIA_NORMAL .$id.'.jpg" border="0"><BR>'.$legenda;?>

config.inc.php

<?php   $config = array();   $config['banco'] = array();   $config['banco']['local'] = 'localhost';			// endereço do servidor de dados   $config['banco']['usuario'] = 'root';			   // usuario do servidor de dados   $config['banco']['senha'] = '';					 // senha do usuario do servidor de dados   $config['banco']['nome'] = 'albumajax';			 // nome do banco de dados      $config['galeria'] = array();   $config['galeria']['path'] = 'fotos\\';			 // \\ pq é windows  -  usar / para linux   $config['galeria']['thumb'] = 'thumb\\';			// \\ pq é windows  -  usar / para linux   $config['galeria']['normal'] = 'fotos\\';		   // \\ pq é windows  -  usar / para linux   $config['galeria']['largura_normal'] = 600;		 // tamanho da foto normal   $config['galeria']['largura_thumb'] = 100;		  // largura da foto miniatura   $config['galeria']['linha'] = 5;					// fotos por linha   $config['galeria']['tamanho'] = '70%';			  // tamanho em porcentagem da tabela   // não mudar nada daqui para baixo   (!defined('BANCO_LOCAL')) ? define('BANCO_LOCAL', $config['banco']['local']) : FALSE;   (!defined('BANCO_USUARIO')) ? define('BANCO_USUARIO', $config['banco']['usuario']) : FALSE;   (!defined('BANCO_SENHA')) ? define('BANCO_SENHA', $config['banco']['senha']) : FALSE;   (!defined('BANCO_NOME')) ? define('BANCO_NOME', $config['banco']['nome']) : FALSE;   (!defined('GALERIA_PATH')) ? define('GALERIA_PATH', $config['galeria']['path']) : FALSE;   (!defined('GALERIA_THUMB')) ? define('GALERIA_THUMB', GALERIA_PATH . $config['galeria']['thumb']) : FALSE;   (!defined('GALERIA_NORMAL')) ? define('GALERIA_NORMAL', GALERIA_PATH . $config['galeria']['normal']) : FALSE;   (!defined('GALERIA_LARGURA_NORMAL')) ? define('GALERIA_LARGURA_NORMAL', $config['galeria']['largura_normal']) : FALSE;   (!defined('GALERIA_LARGURA_THUMB')) ? define('GALERIA_LARGURA_THUMB', $config['galeria']['largura_thumb']) : FALSE;   (!defined('GALERIA_LINHA')) ? define('GALERIA_LINHA', $config['galeria']['linha']) : FALSE;   (!defined('GALERIA_TAMANHO')) ? define('GALERIA_TAMANHO', $config['galeria']['tamanho']) : FALSE;      unset($config);?>

class-banco.inc.php

<?php   require_once('config.inc.php');      class Conexao {	  var $Banco;	  	  function Conexao() {			if (!$this->Banco = @mysql_connect(BANCO_LOCAL, BANCO_USUARIO, BANCO_SENHA)) {			   return FALSE;			}			if (!@mysql_select_db(BANCO_NOME, $this->Banco)) {			   return FALSE;			}			return TRUE;	  }	  	  function Ultimo_ID() {		 $resultado = @mysql_query("SELECT MAX(id) as maxid FROM fotos", $this->Banco);		 if ($valor = @mysql_fetch_array($resultado)) {			return intval($valor['maxid']) + 1;		 } else {			return 0;		 }	  }	  function Registros_Total() {		 $resultado = @mysql_query("SELECT COUNT(id) as total FROM fotos", $this->Banco);		 if ($valor = @mysql_fetch_array($resultado)) {			return intval($valor['total']);		 } else {			return 0;		 }	  }   }?>

class-upload.inc.php

<?php   require_once('config.inc.php');   require_once('class-banco.inc.php');      class Upload {	  var $banco;	  	  function Upload($arquivo, $legenda) {		 settype($legenda, 'string');		 // cria o objeto de conexão com o banco de dados		 $banco = new Conexao();		 $id = $banco->Ultimo_ID();		 // cria o nome do arquivo temporario		 $arquivo_temporario = GALERIA_PATH . $id . "-" . $arquivo['name'] . $this->__Tipo($arquivo['tmp_name']);		 // move o arquivo para um temporario		 if (@move_uploaded_file($arquivo['tmp_name'], $arquivo_temporario)) {			// gera a imagem pequena			if ($this->__Diminuir_Largura($arquivo_temporario, GALERIA_THUMB, $id, GALERIA_LARGURA_THUMB)) {			   // gera a imagem de tamanho normal			   if ($this->__Diminuir_Largura($arquivo_temporario, GALERIA_NORMAL, $id, GALERIA_LARGURA_NORMAL)) {				  // insere a nova imagem no banco				  @mysql_query("INSERT INTO fotos (id, legenda) VALUES (" . $id . ",'" . $legenda . "')", $banco->Banco);				  @unlink($arquivo_temporario);				  return TRUE;			   } else {				  return FALSE;			   }			} else {			   return FALSE;			}		 } else {			echo "Erro ao enviar seu arquivo!";		 }	  }	  	  function __Tipo($imagem) {		 $tipo = getimagesize($imagem);		 // código 2 é JPG		 if ($tipo[2] == 2) {			return 'jpg';		 } elseif ($tipo[2] == 3) { // código 3 é PNG			return 'png';		 } else {			return false;		 }	  }	  function __Diminuir_Largura($imagem, $destino, $id, $largura_aproximada) {		 if (!file_exists($imagem)) {			return FALSE;		 }		 // obtém a extensão pelo mime-type		 $tipo = $this->__Tipo($imagem);		 if (!$tipo) {			return FALSE;		 }		 // nome do arquivo final		 $arquivo_miniatura = $destino . $id;		 // imagem de origem		 if ($tipo == 'jpg') {			$imagem_origem = @imagecreatefromjpeg($imagem);		 } elseif ($tipo == 'png') {			$imagem_origem = @imagecreatefrompng($imagem);		 } else {			return FALSE;		 }		 // obtém as dimensões da imagem original		 $origem_x = @ImagesX($imagem_origem);		 $origem_y = @ImagesY($imagem_origem);		 $x = $origem_x;		 $y = $origem_y;		 // Aqui é feito um cálculo para aproximar o tamanho da imagem ao valor passado em $largura_aproximada.		 if ($x >= $y) {			if ($x > $largura_aproximada) {			   $x1= (int)($x * ($largura_aproximada/$x));			   $y1= (int)($y * ($largura_aproximada/$x));			}			// mantém tamanho original para o thumb.			else {			   $x1= $x;			   $y1= $y;			}		 } else {			if ($y > $largura_aproximada) {			   $x1= (int)($x * ($largura_aproximada/$y));			   $y1= (int)($y * ($largura_aproximada/$y));			}			// mantém tamanho original para o thumb.			else {			   $x1= $x;			   $y1= $y;			}		 }		 $x = $x1;		 $y = $y1;		 // cria a imagem destino		 $imagem_final = @ImageCreateTrueColor($x, $y);		 @ImageCopyResampled($imagem_final, $imagem_origem, 0, 0, 0, 0, $x + 1, $y + 1, $origem_x, $origem_y);		 // o arquivo é gravado		 if ($tipo == 'png') {			@imagepng($imagem_final, $arquivo_miniatura . "." . $tipo);		 } elseif ($tipo == 'jpg') {			@imagejpeg($imagem_final, $arquivo_miniatura . "." . $tipo);		 }		 // a memória usada para tudo isso é liberada.		 @ImageDestroy($imagem_origem);		 @ImageDestroy($imagem_final);		 return TRUE;	  }   }?>

teste-upload.php

<?php   if (!isset($_FILES['arquivo'])) {?>   <form method="post" action="" enctype="multipart/form-data">	  Arquivo<br>	  <input type="file" name="arquivo">	  <br>	  <br>	  Legenda<br>	  <input type="text" name="legenda" size="33">	  <br>	  <br>	  <input type="submit" value="enviar">   </form><?php   } else {	  require_once('class-upload.inc.php');	  $arquivo = isset($_FILES['arquivo']) ? $_FILES['arquivo'] : FALSE;	  $upload = new Upload($arquivo, $_POST['legenda']);	  if ($upload == TRUE) {		 echo "ok";	  }   }?>

e o banco de dados ta assim

/*CREATE DATABASE IF NOT EXISTS `albumajax`;USE `albumajax`;/* fotos*/DROP TABLE IF EXISTS `fotos`;CREATE TABLE `fotos` (  `id` int(11) NOT NULL,  `legenda` varchar(255) NOT NULL,  PRIMARY KEY (`id`));

quando tiver mais coisas eu posto

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.