Foros del Web » Programando para Internet » PHP »

Ayuda, Imagenes al azar.

Estas en el tema de Ayuda, Imagenes al azar. en el foro de PHP en Foros del Web. Buenas gente, estoy necesitando un codigo/script php para mi host de imagenes que muestre imagenes al azar... Osea, que muestre 4 imagenes al azar una ...
  #1 (permalink)  
Antiguo 07/02/2011, 22:24
 
Fecha de Ingreso: diciembre-2010
Mensajes: 180
Antigüedad: 13 años, 4 meses
Puntos: 5
Ayuda, Imagenes al azar.

Buenas gente, estoy necesitando un codigo/script php para mi host de imagenes que muestre imagenes al azar... Osea, que muestre 4 imagenes al azar una al lado de la otra, las imagenes se encuentran todas en "/pictures" Los nombres son genericos, cuando subis una imagen se renombran a un nombre alfanumerico y la extension es segun como la suban :P, pero... Si son imagenes al azar, podrian ser de cualquier tamaño, por eso tambien esta la carpeta "/thumbnails" Donde se sube una copia de cada imagen subida, pero en una resolucion reducida... Osea, mas chica. Si alguien me pudiese ayudar con ese codigo estaria muy agradecido.

POSDATA IMPORTANTE:
El codigo que usaba anteriormente era el siguiente:
random.inc.php
Código PHP:
Ver original
  1. <?php
  2.  
  3. //NUMBER OF RANDOM IMAGES TO SHOW
  4. $images_to_show = 3;
  5. $total = 0;
  6.  
  7.  
  8. $q = "SELECT * FROM `images` WHERE (type = 'member-public') OR (type = 'gallery') OR (type = 'public')";
  9. if(!($result_set = mysql_query($q))) die(mysql_error());
  10. $number = mysql_num_rows($result_set);
  11.  
  12. if ($number) {
  13.   while ($row = mysql_fetch_array($result_set))
  14.   {
  15.     if ($row['type'] == "gallery") {  
  16.       $galleryid = $row['galleryid'];
  17.       $result = mysql_query("SELECT type FROM `galleries` WHERE id = '$galleryid'");
  18.       $row1 = mysql_fetch_row($result);
  19.       $a = $row1[0];
  20.  
  21.       if ($a == "public") {
  22.          $arr[] = $row['id'];
  23.          $total++;
  24.       }
  25.     }
  26.     else {
  27.       $arr[] = $row[0];
  28.       $total++;
  29.     }
  30.   }
  31. }
  32.  
  33.  
  34.  
  35.  
  36. if ($total) {
  37.  
  38.  
  39.   //GET RANDOM IMAGES FROM THE ARRAY
  40.   if ($images_to_show > $total) $images_to_show = $total;
  41.   if ($images_to_show == 1)
  42.      $n[] = 0;
  43.   else
  44.      $n = array_rand($arr,$images_to_show);
  45.  
  46.   echo "</p>
  47.        <table width=100% style=\"border-collapse: collapse\">
  48.        <tr>";
  49.  
  50.   $x = -1;
  51.   for ($i=0; $i < $images_to_show; $i++) {
  52.  
  53.    $id = $arr[$n[$i]];
  54.    $x++;
  55.    if (($x % 5) == 0) echo "</tr><tr>";
  56.  
  57.    echo "<td align=center>";
  58.    echo "<a href=\"show-image.php?id=$id\">";
  59.    echo "<img src='thumb.php?id=$id' style=\"opacity: 1;filter:alpha(opacity=100)\"
  60.                   onmouseover=\"this.style.opacity=0.4;this.filters.alpha.opacity=40\"
  61.                   onmouseout=\"this.style.opacity=1;this.filters.alpha.opacity=100\" />";
  62.    echo "</a></td>";  
  63.   }
  64.   echo "</tr></table>";
  65. }
  66. else
  67.   echo "No se han subido imagenes publicas aún!";
  68.  
  69.  
  70.  
  71. ?>
No lo use mas, ya que dejo de funcionar "como por arte de magia" :S Seguramente algo toque, porque no dejan de funcionar solos los codigos xD, Pero no recuerdo nisiquiera averlo tocado...
Asique, si alguien puede arreglar el codigo muchisimas gracias, y si alguien quiere hacerlo de nuevo, muchas gracias tambien!!
Saludos!
  #2 (permalink)  
Antiguo 07/02/2011, 22:55
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 11 meses
Puntos: 1517
Respuesta: Ayuda, Imagenes al azar.

En el select puedes usar RAND y limitar a 4 solamente. Trata usando RAND en la consulta y luego limita a que muestre 4 solamente.
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #3 (permalink)  
Antiguo 07/02/2011, 23:01
 
Fecha de Ingreso: diciembre-2010
Mensajes: 180
Antigüedad: 13 años, 4 meses
Puntos: 5
Respuesta: Ayuda, Imagenes al azar.

Cita:
Iniciado por abimaelrc Ver Mensaje
En el select puedes usar RAND y limitar a 4 solamente. Trata usando RAND en la consulta y luego limita a que muestre 4 solamente.
Muchas gracias por responder, pero no se ese justamente el problema...
Mira en: www.ironpic.com.ar
Vez la parte que dice "Imagenes al azar"? Fijate que abajo hay 3 cuadritos, pero las imagenes no se ven :S Este problema estara en el "random.inc.php"? O acaso puede estar en el "show-images.php"? Te dejo el codigo en otro coment porque es muy largo
  #4 (permalink)  
Antiguo 07/02/2011, 23:03
 
Fecha de Ingreso: diciembre-2010
Mensajes: 180
Antigüedad: 13 años, 4 meses
Puntos: 5
Respuesta: Ayuda, Imagenes al azar.

show-images.php
Código PHP:
Ver original
  1. <?php
  2.  
  3.  include("db-info.php");
  4.  $link = mysql_connect($server, $user, $pass);
  5.  if(!mysql_select_db($database)) die(mysql_error());
  6.  
  7.  include("session.inc.php");
  8.  include("loadsettings.inc.php");
  9. ?>
  10.  
  11.  
  12.  
  13. <html>
  14.  
  15. <head>
  16.  
  17. <title><? echo $webtitle; ?> -  Hosting de Imagenes</title>
  18. <link rel="stylesheet" href="style.css" type="text/css" />
  19.  
  20. <meta name="description" content="<? echo $description; ?>" />
  21. <meta name="keywords" content="<? echo $keywords; ?>" />
  22.  
  23.  
  24. <script language="JavaScript">
  25.  
  26. function showWindow(id) {
  27.    window.open("show-fullsize.php?id=" + id,"FullsizeImage","menubar=no,width=800,height=600,scrollbars=yes,status=yes,resizable=yes");
  28. }
  29.  
  30. </script>
  31.  
  32. </head>
  33.  
  34.  
  35. <body link=#336699 vlink=#336699 alink=#336699>
  36. <?php include("header.php"); ?>
  37.  
  38. <center>
  39. <div class="content-container">
  40.    
  41.  
  42. <!-- ######################################################################################### -->
  43.  
  44. <?php
  45.  
  46.  
  47. if (isset($_GET["id"])) {
  48.  
  49. $id = $_GET["id"];
  50. if ($id == "") die("Please specify an image id!");
  51.  
  52. $result = mysql_query("SELECT * FROM `images` WHERE id='$id'");
  53. $number = mysql_num_rows($result);
  54. $row = mysql_fetch_array($result);
  55. if (!$number) die("Lo sentimos! La imagen no existe, O fue eliminada por la violacion de los <a href='terms.php'>Terminos de Servicio</a>!");
  56.  
  57. $type = $row['type'];
  58.  
  59.  
  60. //IF IMAGE TYPE IS PRIVATE THEN SHOW THE PASSWORD FORM
  61. if ($type == "member-private") {
  62.  
  63.   if ($row['userid'] != $userid) {
  64.       echo "Esta imagen es privada. Por favor ingrese el password para verla<br><br>";
  65.       echo "<form action='show-image.php' method='POST'>
  66.           <LABEL id='title'>Password: </LABEL> <input type='password' name='password' maxlength='30'>";
  67.       echo "<input type='hidden' name='id' value='$id'> <input type='hidden' name='image' value='member'> ";
  68.       echo "&nbsp; &nbsp; <input type='submit' value='View'></form>";
  69.   }
  70.   else show();
  71.  
  72. }
  73.  
  74.  
  75. //IF THE IMAGE TYPE IS MEMBER PUBLIC THEN SHOW IT!
  76. if ($type == "member-public") {
  77.   show();
  78. }
  79.  
  80.  
  81. //IF THE IMAGE TYPE IS ANONYMOUS PUBLIC THEN SHOW IT!
  82. if ($type == "public") {
  83.   show();
  84. }
  85.  
  86.  
  87. //IF THE IMAGE IS OF A GALLERY THEN:
  88. if ($type == "gallery") {
  89.  
  90.  $q = "SELECT galleryid FROM `images` WHERE id = '$id'";
  91.  if(!($result_set = mysql_query($q))) die(mysql_error());
  92.  $row = mysql_fetch_row($result_set);
  93.  $galleryid = $row[0];
  94.  
  95.  
  96.  //CHECK IF THE GALLERY IN WHICH THE IMAGE IS PRESENT IS PUBLIC OR PRIVATE
  97.  $result_set = mysql_query("SELECT * FROM `galleries` WHERE id = '$galleryid'");
  98.  $row = mysql_fetch_array($result_set);
  99.  $type1 = $row['type'];
  100.  $imguserid = $row['userid'];
  101.  
  102.  
  103.  //IF PRIVATE THEN SHOW THE PASSWORD FORM
  104.  if ($type1 == "private") {
  105.  
  106.     if ($imguserid == $userid) {
  107.        show();
  108.     } else {
  109.      
  110.          if (isset($_SESSION['gallery' . $galleryid]))
  111.               show();
  112.          else {
  113.               echo "Esta galeria es privada. Por favor ingrese el password para verla<br><br>";
  114.               echo "<form action='show-image.php' method='POST'>Password: <input type='password' name='password' maxlength='30'>";
  115.               echo "<input type='hidden' name='id' value='$id'>  <input type='hidden' name='image' value='gallery'>";
  116.               echo "&nbsp; &nbsp; <input type='submit' value='View'></form>";
  117.          }
  118.     }
  119.    
  120. }
  121.  else
  122.    show();
  123.  
  124. }
  125.  
  126.  
  127.  
  128.  
  129.  
  130. //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
  131.  
  132.  
  133. }
  134. else {
  135.  
  136.     //IF PASSWORD IS SUBMITTED
  137.     if (isset($_POST["password"]))  {
  138.  
  139.        $id = $_POST["id"];
  140.        $image = $_POST["image"];
  141.  
  142.        //GET THE ASSOCIATIVE USER ID  
  143.        $imguserid = getUserId($id);
  144.  
  145.        //EXTRACT HIS USER PASS
  146.        $r = mysql_query("SELECT userpass FROM `members` WHERE id = '$imguserid'");
  147.        $row1 = mysql_fetch_row($r);
  148.        $userpass = $row1[0];
  149.  
  150.        //THEN CHECK IT.. IF CORRECT THEN SHOW
  151.        if ($_POST["password"] != $userpass)
  152.           echo "Lo sentimos! Usted ingreso un password incorrecto.";
  153.        else
  154.           show();
  155.    }
  156.  
  157. }
  158.  
  159.  
  160.  
  161.  
  162. //THIS FUNCTION DISPLAYS THE IMAGE
  163. function show() {
  164.  
  165.   global $id; global $session; global $userid;
  166.  
  167.   include("loadsettings.inc.php");
  168.  
  169.  
  170.   $q = "SELECT * FROM `images` WHERE id = '$id'";
  171.   if(!($result_set = mysql_query($q))) die(mysql_error());
  172.   $row = mysql_fetch_array($result_set);
  173.  
  174.   $thumb = $row['thumb'];
  175.   $image = $row['image'];
  176.  
  177.   //UPDATE VIEWS COUNT AND LAST ACCESS DATE
  178.   $views = $row['views'] + 1;
  179.   $access = date("y-m-d");
  180.   $r = mysql_query("UPDATE `images` SET views = '$views', access = '$access' WHERE id = '$id' ");
  181.  
  182.  
  183.   $imguserid = getUserId($id);
  184.  
  185.   $own = false;
  186.   if ($imguserid != -1) {
  187.        
  188.        if ($userid == $imguserid)
  189.           $own = true;
  190.  
  191.        $r = mysql_query("SELECT username FROM `members` WHERE id = '$imguserid'");
  192.        $row1 = mysql_fetch_row($r);
  193.        $username = $row1[0];
  194.   }
  195.   else $username = "Anonymous";
  196.    
  197.  
  198.  
  199.   echo "<center>";
  200.   echo "<br><LABEL id='title'>Visitas:</LABEL> $views";
  201.   echo "<br><LABEL id='title'>Subida el Día:</LABEL> {$row['date']}";

Es muy largo T.T, Sigo abajo
  #5 (permalink)  
Antiguo 07/02/2011, 23:03
 
Fecha de Ingreso: diciembre-2010
Mensajes: 180
Antigüedad: 13 años, 4 meses
Puntos: 5
Respuesta: Ayuda, Imagenes al azar.

Código PHP:
Ver original
  1. //***********************************************************************************
  2.  
  3.      //Check if image size is bigger than 800 X 800 then make it small to atleast 800 but proportionally
  4.      $img = imagecreatefromunknown($image);
  5.                                  
  6.      $mainWidth = imagesx($img);
  7.      $mainHeight = imagesy($img);
  8.              
  9.      if (($mainWidth > 800) || ($mainHeight > 800))
  10.      {
  11.           $a = ($mainWidth >= $mainHeight) ? $mainWidth : $mainHeight;
  12.           $div = $a / 800;
  13.           $mainWidth = intval($mainWidth / $div);
  14.           $mainHeight = intval($mainHeight / $div);
  15.  
  16.           echo "<br><br><a href='$image' title='Click aqui para ver la imagen en tamaño original' target='_blank'>
  17.                   <img src='$image' border=1 width='$mainWidth' height='$mainHeight'>
  18.                   </a>";
  19.      }
  20.      else {
  21.          echo "<br><br><img src='$image' border='1'>";
  22.      }
  23.  
  24.   //***********************************************************************************
  25.  
  26.  
  27.  
  28.   echo "<br><br><LABEL id='title'>Detalles:</LABEL> {$row['details']}";
  29.   echo "<br><LABEL id='title'>Subida Por:</LABEL> $username";
  30.   echo "<br><br><LABEL id='title'>Tags:</LABEL><br>{$row['tags']}";
  31.  
  32.   echo "<br><br><br><br>";
  33.  
  34.   echo "<div class='emailBox'>
  35.         <form method='POST' action='email.php'>
  36.         <LABEL id='title'>Envia esta imagen a un amigo via Email:</LABEL><br> &nbsp; <input type='text' size='20' name='email'>&nbsp; &nbsp;
  37.         <input type='submit' value='Enviar' name='emailImage'>
  38.         <input type='hidden' name='id' value='$id'>
  39.         <br>En caso de multiples emails, separar emails con comas (,)
  40.         </form></div>";
  41.  
  42.   echo "<br><br><a href='report.php?id=$id'><img src='images/abuse.png' border=0></a>";
  43.  
  44.   if ($session == true)
  45.      echo "&nbsp;  <a href='addfavourite.php?id=$id'><img src='images/favourites.png' border=0></a>";
  46.  
  47.  
  48.   echo "<br><br><br><br>";
  49.  
  50.   //*****************************************************************************************************
  51.  
  52.  
  53. if ($imguserid != -1) {  
  54.  
  55.   $r = mysql_query("SELECT * FROM `comments` WHERE imageid = '$id' ORDER BY id DESC");
  56.   $n = mysql_num_rows($r);  
  57.  
  58.  
  59.   echo "<div style='FLOAT: left; WIDTH: 500px; TEXT-ALIGN: left; BORDER-RIGHT: #42679c 2px solid;
  60.                     PADDING-LEFT: 20px; PADDING-RIGHT: 20px; HEIGHT: 300px; MARGIN-RIGHT: 20px'>";
  61.   echo "<h2><u>Comentarios</u></h2>";
  62.  
  63.   if ($n) {
  64.  
  65.      $ccount = -1;
  66.      while ($row1 = mysql_fetch_array($r)) {
  67.        $comment = str_replace("\n", "<br>", $row1['comment']);
  68.      
  69.        $ccount++;
  70.        if ($ccount == 5)
  71.          echo "<br><a href='#' style='FONT-SIZE: 16px'
  72.                  onclick=\"getElementById('allcomments').style.display='block'; this.style.display='none'\">
  73.                  Ver todos los comentarios</a>
  74.                <div style='display: none' id='allcomments'>";
  75.  
  76.        echo "<div class='commentbox'> $comment ";
  77.        if ($own == true)
  78.            echo "<br><a href='deletecomment.php?id={$row1['id']}'>Delete</a>";
  79.        echo "</div>";
  80.      }
  81.       if ($ccount > 4) echo "</div>";  
  82.  
  83.   }
  84.   else
  85.       echo "<div class='commentbox'>No hay comentarios para esta imagen!</div>";
  86.  
  87.    
  88.   if ($session == true) {
  89.  
  90.     echo "<form method='POST' action='postcomment.php'>
  91.           <br><h2>Publicar Comentario</h2>
  92.           <textarea cols=40 rows=4 name='comment'></textarea><br>
  93.           <input type='hidden' name='id' value='$id'>
  94.           <input type='submit' value='Publicar' name='postcomment'>
  95.           </form> <b>Caracteres Maximos: 200</b>
  96.          ";    
  97.     }
  98.    echo "</div>";
  99.  
  100. }
  101.  
  102.  
  103.   //********************************************************************************************************
  104.  
  105.   echo "<div style='TEXT-ALIGN: left'>
  106.         <h2><u>Codigos:</u> </h2>";
  107.   echo "<table style='border-collapse: collapse'><tr><td>";
  108.  
  109.   echo "<LABEL id='title'>HTML:</LABEL><br><input type='text' size=50 onclick=\"this.select();\" value=\"<a href='{$website}/show-image.php?id=$id'> <img src='{$website}/{$thumb}' alt='Image Hosting' border='0'> </a>\">";
  110.   echo "<br><br>";
  111.    
  112.  
  113.   echo "<LABEL id='title'>Codigo BB:</LABEL><br><input type='text' size=50 onclick=\"this.select();\" value=\"[URL={$website}/show-image.php?id={$id}] [IMG]{$website}/{$thumb}[/IMG][/URL]\">";
  114.   echo "<br><br>";
  115.  
  116.  
  117.   echo "<LABEL id='title'>Link Directo:</LABEL><br><input type='text' size=50 onclick=\"this.select();\" value=\"{$website}/{$image}\">";
  118.   echo "<br><br>";
  119.  
  120.  
  121.   echo "<LABEL id='title'>Link Directo (BB Code):</LABEL><br><input type='text' size=50 onclick=\"this.select();\" value=\"[URL={$website}] [IMG]{$website}/{$image}[/IMG][/URL]\">";
  122.   echo "<br><br>";
  123.  
  124.   echo "<LABEL id='title'>URL:</LABEL><br><input type='text' size=50 onclick=\"this.select();\" value=\"{$website}/show-image.php?id=$id\">";
  125.  
  126.   echo "</td></tr></table></div>";
  127.  
  128.  
  129.  
  130.   //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
  131.  
  132.   echo "<p style='CLEAR: both'>";
  133.   echo "<br><br>-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br><br>";
  134.   include("random.inc.php");  
  135.  
  136.  
  137. }
  138.  
  139.  
  140.  
  141. // Returns the userid of image.. if its a gallery image it retrieves the userid from the galleries table
  142. function getUserId($id) {
  143.  
  144.  $userid = "";
  145.  $result = mysql_query("SELECT * FROM `images` WHERE id='$id'");
  146.  $row = mysql_fetch_array($result);
  147.  $type = $row['type'];
  148.  
  149.  if ($type == "gallery") {
  150.  
  151.       $q = "SELECT galleryid FROM `images` WHERE id = '$id'";
  152.       if(!($result_set = mysql_query($q))) die(mysql_error());
  153.       $row = mysql_fetch_row($result_set);
  154.       $galleryid = $row[0];
  155.  
  156.       $result_set = mysql_query("SELECT userid FROM `galleries` WHERE id = '$galleryid'");
  157.       $row = mysql_fetch_row($result_set);
  158.       $userid = $row[0];
  159.  }
  160.  else {
  161.  
  162.       $q = "SELECT userid FROM `images` WHERE id = '$id'";
  163.       if(!($result_set = mysql_query($q))) die(mysql_error());
  164.       $row = mysql_fetch_row($result_set);
  165.       $userid = $row[0];
  166.  }
  167.  
  168.  
  169.  return $userid;
  170.  
  171. }
  172.  
  173.  
  174.  
  175.  
  176.  
  177. function findExtension ($filename)
  178. {
  179.    $filename = strtolower($filename) ;
  180.    $exts = split("[/\\.]", $filename) ;
  181.    $n = count($exts)-1;
  182.    $exts = $exts[$n];
  183.    return $exts;
  184. }
  185.  
  186.  
  187. function imagecreatefromunknown($path) {
  188.  
  189.    $ext = findExtension($path);
  190.    
  191.    switch ($ext) {
  192.       case "jpg":
  193.         $img = imagecreatefromjpeg($path);
  194.         break;
  195.       case "gif":
  196.         $img = imagecreatefromgif($path);
  197.         break;
  198.       case "png":
  199.         $img = imagecreatefrompng($path);
  200.         break;
  201.   }
  202.  
  203.   return $img;
  204. }
  205.  
  206.  
  207.  
  208.  
  209.  
  210. ?>
  211.  
  212. <!-- ######################################################################################### -->
  213.  
  214. <?php  include("footer.php"); ?>
  215.  
  216.  
  217. </div>
  218. </center>
  219. </body>
  220. </html>

Saludos!!

Última edición por SonrisaCs; 08/02/2011 a las 14:09

Etiquetas: imagenes
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 16:02.