reduce the size of an image in the database

Asked

Viewed 677 times

0

I have a table that shows the contents of a database, one of the contents is an image, call the image as follows: <td><?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $books->Image ).'"/>'; ?> </td>

but the image appears too large, I would like to know how to change the image size?

3 answers

5

We should take some care whenever we use the sizes of an image through the height and width attributes. The main one is the ratio between the width and the height of an image.

If these attributes are not known, first we should get them through the function PHP getimagesize.

list($width, $height, $type, $attr) = getimagesize("../images/Imagem005.jpg");

Returns an array with 4 elements. Index 0 contains the image width in pixels. Index 1 contains the height. Index 2 is an indication of the image type: 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(Motorola byte order), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM. These values correspond to the IMAGETYPE constants that were added in PHP 4.3. Index 3 is a string with the correct height="yyy" width="xxx" that can be used directly in an IMG tag. getimagesize

As we only care about the height and width attributes we will use

 list($width, $height) = getimagesize("../images/Imagem005.jpg");
 //nova largura
 $newWidth = 200;

 //nova altura
 $newHeight = ($newWidth*$height)/$width;

 echo "<img src=\"../images/Imagem005.jpg\" width=\"".$newWidth."\" height=\"".$newHeight."\"/>";

In your case the img tag would look like this:

   echo '<img src="data:image/jpeg;base64,'.base64_encode( $books->Image ).'" height='.$newHeight.' width='.$newWidth.'/>';

On the other hand, leaving PHP aside, just indicate the width in the img tag that browsers automatically calculate the height.

  • It seems too much to me. I would only use CSS, it’s more performant, and the result is the same. With auto height the browser calculates for us the height, hence you need less processing, and as it is on the client side is "cachable".

1


look I never used database, but from what I saw if you use the <img src=""> to call the picture, then the width and the height should work, try adding something like this here <img src="" height="150" width="150">

<td><?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $books->Image ).'" height="150" width="150"/>'; ?> </td>

1

You can also use CSS to change the image size. And I recommend that you do it proportionally, I mean, just apply the width so it wouldn’t look "forced".

Your PHP code with resized CSS class.

<td><?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $books->Image ).'" class="resized"/>'; ?> </td>

CSS code

.resized {
  width: 150px;
  height: auto;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.