Marcus
Marcus

Reputation: 55

Set imagesize in <img></img>, when getting it from a db

I have an "echo" that is getting an image from my database, but, when I upload it, it automatically changes size down to 200x113px. I don't want the picture be scaled that much, I want it to be like:

I want to have a "box" that's about 500x500px, so for example when I upload a picture that's longer than 500px, it will shrink to only 500px wide, but keep its proportions.

Summary: I want to set a max-size for the picture to be when I get it to the screen with the code. And it should fit in to that size and keep its proportions.

Here's my code that gets the image:

{echo "<tr><td colspan='2'><img src='http://xxxx.se/ok/eventbilder/"   . $row['photo'] .  "'></td></tr>";}

Upvotes: 2

Views: 106

Answers (4)

Sahil Popli
Sahil Popli

Reputation: 1993

You can also give a class to <img> like <img class="dbimg" src="from database"></img>

and give all styles to that class

.dbimg{
width:auto;
max-width:500px; //by only define width it will automatically takes up height as per its proportions 
//other styling  
}

and the advantage to use this approach is

1.you can make any no of img with one single class no need to write code every time

and

2.you can make many combinations if you have more images like that to show in different sizes

Upvotes: 0

Gianluca Ghettini
Gianluca Ghettini

Reputation: 11628

you need adaptive scaling: this function takes your image path and returns $x and $y scaled accordingly. Here we assume a container box $w pixels in width and $h pixels in height

   // get size
   $size = getimagesize($your_image_file_path);
   $x = $size[0];
   $y = $size[1];

   // container box
   $w = 500;
   $h = 500;

   $ratio = $x / $y;    

   // resize image
   if($x > $w)
   {
      $x = $w;
      $y = floor($x / $ratio); 
   }

   if($y > $h)
   {
      $y = $h;
      $x = floor($y * $ratio); 
   }

Upvotes: 0

Sumit Bijvani
Sumit Bijvani

Reputation: 8179

{echo "<tr><td colspan='2' style='width:500px;height:500px;'><img src='http://xxxx.se/ok/eventbilder/"   . $row['photo'] .  "'></td></tr>";}

Upvotes: 0

Gung Foo
Gung Foo

Reputation: 13558

use this CSS:

img {
  max-width: 500px;
}

or set a width on your td and make the images width 100%. make sure you only set either height or width, otherwise the image won't (automatically) keep it's ratio.

Upvotes: 1

Related Questions