FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


Auto width\height if picture is wider than a given variable





ranzon
hi.

if i have a picture, with url..
i want to print the picture, but if the width of the picture is more than the variable $maxwidth it sets the width of picture to maxwidth..
then its also sets the height of picture so the picture got a height so the picture is not streched..

please help me.. Smile
Simulator
Code:
<?php


  $connection = mysql_connect($host,$user,$password)   
       or die ("couldn't connect to server");
  $db = mysql_select_db($database,$connection)         
       or die ("Couldn't select database");

         $result2 = mysql_query("SELECT pic FROM pics WHERE id = '".mysql_escape_string($_GET["id"])."'
         ORDER BY pic ASC");
             for ($i=0; $i<mysql_num_rows($result2); $i++)
              {

              $pic2 = mysql_result($result2,($i));

         
# Constants

$mAX_WIDTH = 125;
$mAX_HEIGHT = 180;

# Get image location
$image_path = $pic2;

# Load image
$img = null;
$ext = strtolower(end(explode('.', $image_path)));
if ($ext == 'jpg' || $ext == 'jpeg') {
    $img = @imagecreatefromjpeg($image_path);
} else if ($ext == 'png') {
    $img = @imagecreatefrompng($image_path);
# Only if your version of GD includes GIF support
} else if ($ext == 'gif') {
    $img = @imagecreatefromgif($image_path);
}

# If an image was successfully loaded, test the image for size
if ($img) {

    # Get image size and scale ratio
    $width = imagesx($img);
    $height = imagesy($img);
    $scale = min($mAX_WIDTH/$width, $mAX_HEIGHT/$height);

    # If the image is larger than the max shrink it
    if ($scale < 1) {
        $new_width = floor($scale*$width);
        $new_height = floor($scale*$height);

        # Create a new temporary image
        $tmp_img = imagecreatetruecolor($new_width, $new_height);

        # Copy and resize old image into new image
        imagecopyresized($tmp_img, $img, 0, 0, 0, 0,
                         $new_width, $new_height, $width, $height);
        imagedestroy($img);
        $img = $tmp_img;       
    }   
}

# Create error image if necessary
if (!$img) {
    $img = imagecreate($mAX_WIDTH, $mAX_HEIGHT);
    imagecolorallocate($img,0,0,0);
    $c = imagecolorallocate($img,70,70,70);
    imageline($img,0,0,$mAX_WIDTH,$mAX_HEIGHT,$c2);
    imageline($img,$mAX_WIDTH,0,0,$mAX_HEIGHT,$c2);
}
# Display the image
header("Content-type: image/gif");
imagegif($img);
}


?>


Ok lets break it down

Code:
<?php


  $connection = mysql_connect($host,$user,$password)   
       or die ("couldn't connect to server");
  $db = mysql_select_db($database,$connection)         
       or die ("Couldn't select database");

         $result2 = mysql_query("SELECT pic FROM pics WHERE id = '".mysql_escape_string($_GET["id"])."'
         ORDER BY pic ASC");
             for ($i=0; $i<mysql_num_rows($result2); $i++)
              {

              $pic2 = mysql_result($result2,($i));
}


?>


That as you can tell connects to my database and gets the location for a picture, now the For loop isnt really that important, I just use it to make sure I get it right, its not needed but I like to use it. $pic2 is now the location of the picture

Code:
<?php
   
# Constants

$mAX_WIDTH = 125;
$mAX_HEIGHT = 180;

# Get image location
$image_path = $pic2;

?>


Now this just defines the max height and width, it also changes the $pic2 variable to $image_path, this again is not needed, I just wanted to change the name of it and didnt bother to go back up to the top.

Code:
<?php

# Load image
$img = null;
$ext = strtolower(end(explode('.', $image_path)));
if ($ext == 'jpg' || $ext == 'jpeg') {
    $img = @imagecreatefromjpeg($image_path);
} else if ($ext == 'png') {
    $img = @imagecreatefrompng($image_path);
# Only if your version of GD includes GIF support
} else if ($ext == 'gif') {
    $img = @imagecreatefromgif($image_path);
}

?>


Now this little beauty Im particularly proud of, it finds out what type of file it is.

Code:
<?php

# If an image was successfully loaded, test the image for size
if ($img) {

    # Get image size and scale ratio
    $width = imagesx($img);
    $height = imagesy($img);
    $scale = min($mAX_WIDTH/$width, $mAX_HEIGHT/$height);

    # If the image is larger than the max shrink it
    if ($scale < 1) {
        $new_width = floor($scale*$width);
        $new_height = floor($scale*$height);

        # Create a new temporary image
        $tmp_img = imagecreatetruecolor($new_width, $new_height);

        # Copy and resize old image into new image
        imagecopyresized($tmp_img, $img, 0, 0, 0, 0,
                         $new_width, $new_height, $width, $height);
        imagedestroy($img);
        $img = $tmp_img;       
    }   
}

?>


Well if the image is found and is a file type that is listed, then it resizes the image, to your max height and width, but still keeps it in proportion.

Code:
<?php

# Create error image if necessary
if (!$img) {
    $img = imagecreate($mAX_WIDTH, $mAX_HEIGHT);
    imagecolorallocate($img,0,0,0);
    $c = imagecolorallocate($img,70,70,70);
    imageline($img,0,0,$mAX_WIDTH,$mAX_HEIGHT,$c2);
    imageline($img,$mAX_WIDTH,0,0,$mAX_HEIGHT,$c2);
}

?>


Then if the image is not found all you get is a big black rectangle in the sizes you have stated for your thumbnail.

Code:
<?php

# Display the image
header("Content-type: image/gif");
imagegif($img);
}

?>


And last you have your image created. So what now, and how do I use it, I hear you ask. Well its simple. Just save that as a file like thumb.php, and when you want to use it just use the following code:

Code:

      $result3 = mysql_query("SELECT id FROM pics");
             for ($i=0; $i<mysql_num_rows($result3); $i++)
              {
         $id = mysql_result($result3,($i));
      
   Echo <img src='thumb.php?id=$id&type=thumb' border='0' alt='users image'>";
}


Now this is how you put out your image, the last file, thumb.php is only the link for your image, NEVER USE IT IN THE FILE WHERE YOU WANT TO SHOW THE PICTURE. Now once again, you connect to the database, and you get the ID of the pic, this is the number of your pic in your database. If you go back to the thumb.php code you find that the only pic that is selected in the database is the one that has the ID of the one you are looking for in $id,

So what do you think
ranzon
ok. it worked fine until i included it...
now its printing this huge thing of errormessage or what it is:
Quote:
Warning: Cannot modify header information - headers already sent by (output started at /var/www/web149/html/index.php:11) in /var/www/web149/html/sponsors.php on line 66
GIF87at44DC"D##D4D%% "hB,5lE$Jb4̦l|Z$DZ$b4dfd CGG4$4tr\ܪp,"$"$sYd. R$(`V,+  |ljl9;&rT$, Ȇd4*eDiTBH XԎlԪ#dt+ lF DBM7$$f4=H<2lRTwv뽼dVT\o/"$̂TFD|L䚜VV̚trL fdl9$2<|RLN$t{q|yxwwdnlɉ4B<^N0\^\$%'TNdVTnDn,L>K'Wink>$D,4(<,IJ.! .,Tt,<6t&t4$24:::=':dLF8zt<.,,Z<Y*lbD-&  T^$쬬DE:T<4h(Ndp%C ! 2h]>fsj8Pt c ;.J@6 ڸ3ƐE v h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y!iY_9Ayh(҂(vt-*84KFt ᘃY(aXH :i)BoiHqX]Fom D+ԐKxo&^I݉>H ?ȕI;IIIy4ICݸ빛RiYy(72؟i9ّc?NɌKII ,Z#H!(6:SyH94ٜ1N2)nILa=J IEZXYxY'șGV!IqٞwɐI 7.S.6zi]Je0 >G)9U ?y ejNK>ڕԍEEֹ 橢rڟG%E)zM y }ErXzjdr~`*AD@ĩ\ڤ?:I)L!ڏ vJ ؉~4t[2 sɮZ IL٘p l 'ZAIH}ɗKNQኣ[]'@ک%ӗlL\Haϛ)#crGE1m*o|Tj0U]wOΣ[˧T,پxꤨ+»7k՛ŝH)kZK6_|l?z]C Ϧ|[YHܓ+ۺ-[L]K+kÑ=8+ޅMB|R֊:kMM\mT(r,j#-w`Au="ӭH*K̪a[\ޑ),P[vcJ%k*WE ٩l6ZxH\- 6HnZ|I .̂ی/K1k-J[;؛n x [:⼎h9Xʇ<q>{=b=,f螝ƈ=ߘ Ԉ\iZ)ؓ;„H }E.HZt 'yLX(jQ;
Simulator
Thats because you are using it in a file, it must be put in a seperate file, say thum.php and just put the id number of the row where the image is into a get thingey like thumb.php?id="ID NUMBER HERE" get me? So you'll have:

<img src="thumb.php?id=ID NUMBER HERE" />
ranzon
but i want to show all the images in the database.. how to do that?

i have changed the mysql stuff on top to:
Code:
include("db.php");

         $result2 = mysql_query("SELECT * FROM sponsors ORDER BY id DESC");
             for ($i=0; $i<mysql_num_rows($result2); $i++)
              {

              $pic2 = mysql_result($result2,$i,"url");
Simulator
Code:
include("db.php");

         $result2 = mysql_query("SELECT * FROM sponsors WHERE id = '".mysql_escape_string($_GET["id"])."'  ORDER BY id DESC");
             for ($i=0; $i<mysql_num_rows($result2); $i++)
              {

              $pic2 = mysql_result($result2,($i));


Thats what you need there, and then for the page and then on the page where you want the ads to be shown put the following:

Code:

$query = "SELECT * FROM sponsors ORDER BY id DESC";
$query = mysql_query($query);
while($row = mysql_fetch_array($query))
{
extract($row);
echo "<img src=\"thumb.php?id=".$id."\" />";
}


Should work, so long as in your database you have a row called ID, and each one is different
ranzon
actually now the script is like this:
Code:
<?php
include("db.php");
$query="SELECT * FROM sponsors ORDER BY id DESC";
$result=mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
mysql_close();

$i=0;
while ($i < $num) {

$pic2=mysql_result($result,$i,"url");

       
# Constants

$mAX_WIDTH = 149;
$mAX_HEIGHT = 200;

# Get image location
$image_path = $pic2;

# Load image
$img = null;
$ext = strtolower(end(explode('.', $image_path)));
if ($ext == 'jpg' || $ext == 'jpeg') {
    $img = @imagecreatefromjpeg($image_path);
} else if ($ext == 'png') {
    $img = @imagecreatefrompng($image_path);
# Only if your version of GD includes GIF support
} else if ($ext == 'gif') {
    $img = @imagecreatefromgif($image_path);
}

# If an image was successfully loaded, test the image for size
if ($img) {

    # Get image size and scale ratio
    $width = imagesx($img);
    $height = imagesy($img);
    $scale = min($mAX_WIDTH/$width, $mAX_HEIGHT/$height);

    # If the image is larger than the max shrink it
    if ($scale < 1) {
        $new_width = floor($scale*$width);
        $new_height = floor($scale*$height);

        # Create a new temporary image
        $tmp_img = imagecreatetruecolor($new_width, $new_height);

        # Copy and resize old image into new image
        imagecopyresized($tmp_img, $img, 0, 0, 0, 0,
                         $new_width, $new_height, $width, $height);
        imagedestroy($img);
        $img = $tmp_img;       
    }   
}

# Create error image if necessary
if (!$img) {
    $img = imagecreate($mAX_WIDTH, $mAX_HEIGHT);
    imagecolorallocate($img,0,0,0);
    $c = imagecolorallocate($img,70,70,70);
    imageline($img,0,0,$mAX_WIDTH,$mAX_HEIGHT,$c2);
    imageline($img,$mAX_WIDTH,0,0,$mAX_HEIGHT,$c2);
}
# Display the image
imagegif($img);
$i++;

?>
Simulator
And does that work Confused
ranzon
Simulator wrote:
And does that work Confused

no. ive getting the _BIG_ error..
Antoine_935
OR:
you can get image's size with function getimagesize (or something like this)
then, test whether it's greater than the max value, and if it is, then put a
Code:
style="width: MAX_SIZEpx; height:MAX_HEIGHTpx;"
in the <img> tag.

OR:
simply put this in <img> tag, withotu any PHP check
Code:
style="max-width: MAX_WIDTHpx; max-height: MAX_HEIGHTpx;"
It should work nice too Wink
Related topics
picture slide show (java)
picture-dept.
Frankfurt Motor Show, 2005
xbox 360 the big picture
Justification for War in Iraq
Fortran Tutorials(77)
writing COM components in Perl
Joking....
A paper on an abstract musical idea. Cary Angell
phpbb cash mod problemos
[JavaScript]: Checking for undefined values
Grand Theft Auto - San Andreas for PC...
Randomness is an illusion. [philosophy/science]
EMP Resistant Vehicles ?
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.