We currently use another server (well, the same server but different account and domain) to serve images for our website.
It currently works like this:
http://images.example.com?src=imagepath&w=300&h=500&q=75.
This does automatic image resizing based on the w=300
and h=400
that we provide to the URL (pixels).
However, the site is for a car dealership and we don't always want to specify the width. Sometimes we need percentage widths, as the site is responsive, and also, not all images are the same size to begin with, so it leads to distortion if we say all images are 700 wide.
Is it possible to have this kind of image resizing external server but using percentages?
We use Apache, PHP
and the images are accessed via directory names based on criteria in the database for that car, so for example images/ford/focus/AA136YH/image1.jpg
.
TL/DR Question: How can we serve images from external PHP
server with percentage widths instead of specifying fixed width and/or height?
I suggest CSS like the other answers; if you don't want this, use GD Lib but keep in mind this will use some CPU resources everytime the image is requested.
If you can't use CSS, use a script like the below but cache the scaled image, using Memcached for example or disc storage.
GD Lib resizing:
<?php
$filename = $_GET['src'];
$percent = intval($_GET['q']) / 100;
if (!file_exists($filename)) {
die('image does not exist');
}
list($width, $height) = getimagesize($filename);
$newWidth = $width * $percent;
$newHeight = $height * $percent;
$scaled = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($filename);
imagecopyresized($scaled, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
header('Content-Type: image/jpeg');
imagejpeg($scaled);
imagedestroy($scaled);
You'd load the image from the server at some pre-determined maximum size and then let CSS do the re-sizing. Your HTML would look like this:
<img src="http://images.example.com?src=imagepath&w=300&h=500&q=75" class="responsive" />
And your CSS would look like this:
.responsive {
width: 50%;
height: auto;
}
This will resize the image to 50% width and set the height according to it's original aspect ratio.
i would use this css markup for the images
img {
width:100%;
}
and let the context lead the appropriate sizing of the image. for context i mean the parent div
containing the image