So I am building a php page and trying to display images in a table
Currently my code looks like this:
echo "<h3>TEST TABLE</h3>";
echo "<table width='350px' border='1px'>"; //blah blah
while ($row2 = $res2->fetch_assoc()){ // takeing data from database as url is stored in mysql database
echo"<tr><td>".$row2['Name']."</td>";
echo"<td>".$row2['Description']."</td>";
$image =$row2['Img'];
$imageData = base64_encode(file_get_contents($image));
echo '<td><img src="data:image/jpeg;base64,'.$imageData.'"></td>'; //So this chunk is how I capture img from url and display
echo "<td><small>$Info</small></td></tr>";
}
echo "</table>";
I did capture and display the images by url successfully. However I am not so sure how I can resize the imgs so they would be in a fixed size like 500x500 or so. Any advice and suggestion would be appreciated! Thanks!
You can simply pass width, height to image tag like:
<img src="data:image/jpeg;base64,'.$imageData.'" height="500" width="500">
where height="500" width="500" means 500px.
And if you want that each image would be of 500x500, than you have to define it at the time of image upload.
Something like this will work,
Fetch the image and store it in an another variable and call the php resizer function and allow php itself to do thumbnails efficiently.
Even you can customize it,
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb);
If you have multiple images on the page, it would be better to fetch them already resized from the server by specifying the required image size in the URL:
https://example.com/image.jpg
https://example.com/w_120,h_120,c_fill/image.jpg
It can be easily implemented as a Google Cloud Function (see image-resizing npm package):
$ yarn add image-resizing
const { createHandler } = require("image-resizing");
module.exports.img = createHandler({
// Where the source images are located.
// E.g. gs://s.example.com/image.jpg
sourceBucket: "s.example.com",
// Where the transformed images needs to be stored.
// E.g. gs://c.example.com/image__w_80,h_60.jpg
cacheBucket: "c.example.com",
});
Related
I have a folder named images, where I have images like: hero.jpg, hero_medium.jpg, hero_small.jpg. My question is, if this is the correct solution, or maybe it would be better to have one big picture and change its size via URL. At the moment I have managed to do something like this in img.php file in images folder:
<?php
header('Content-Type: image/jpeg');
$filename = 'hero.jpg';
list($width_orig, $height_orig) = getimagesize($filename);
if(empty($_GET['w'])){
$width = $width_orig;
} else {
$width = $_GET['w'];
}
$height=$width;
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($image_p, null, 100);
I would like to change the size of a photo by a friendly URL, i.e. hero_medium.jpg to e.g. 768px in php using htaccess, is such a thing possible?
EDIT: Apple has an interesting situation on its website. The URL for the images looks like the following: https://www.apple.com/newsroom/images/environments/stores/Apple_Tower-Theatre-now-open-in-downtown-LA-store-interior-wide-shot_062421_big.jpg.medium.jpg, why is there big.jpg.medium.jpg? I suspect they may be doing something with htaccess file, because having that many photos it would be unreadable, so I think they are resizing them dynamically. What do you think?
EDIT 2: I noticed that it takes much longer to load and change the image via php, is this actually a good idea?
If you just want to return an image of adequate dimensions, there are several ways to achieve this.
Maybe you want to have a look at this:
https://css-tricks.com/a-guide-to-the-responsive-images-syntax-in-html/
I have stored multiple images in base64 inside my database. I get images using php as image path. But I want to reduce size of my image when decoding it from base64, because it slows down my app if I load full size image. (Full size image I need just in backend).
/*
DB stuff getting base64 string from database
$img = base64 string (can be with 'data:image/jpg;base64,' in front, thats for the str_replace())
*/
if($img){
header("Content-Type: image/png");
echo base64_decode(str_replace("data:image/jpg;base64,","",$img));
}
Everything works nice this way. I use it like this:
<img src="http://example.com/getimg.php?id=4" />
or in css. I need this because of security reasons, I cant store any image on server, also in path I have access_token variable, so random person cant see images.
Is there a way to do this without storing the actual image in server?
You can use imagecreatefromstring and imagecopyresized.
Live example here
<?php
if ($img) {
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
$data = base64_decode($img);
$im = imagecreatefromstring($data);
$width = imagesx($im);
$height = imagesy($im);
$newwidth = $width * $percent;
$newheight = $height * $percent;
$thumb = imagecreatetruecolor($newwidth, $newheight);
// Resize
imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb);
}
using the example given at http://www.php.net/manual/en/function.imagecopyresized.php ... how to get image sizes afterward using getimagesize() function?
CODE:
<?php
if(isset($_FILES['images'])){
//TEST1:
$img = resize_this_image_now($_FILES['images']['tmp_name']);
//TEST2:
$img = resize_this_image_now($_FILES['images']['name']);/// This Drastically failed.
$new_image = getimagesize($img);
var_dump($new_image[0]);// I guessed this should have printed out the WIDTH_OF_THE_IMAGE... but, it prints some NON_READABLE stuffs (why?)
}
// The PHP.NET CODE in a Function
function resize_this_image_now($filename){
// File and new size
// $filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
return imagejpeg($thumb);
}
?>
All I want is to get the Size of the Image.... also, is it possible to do something like:
$_FILES['images']['tmp_name'] = $the_newly_resized_image_returned_from_the_PHP_dot_NET_code'; .... So that the ['images']['tmp_name'] will now have as source this new image??
Any suggestion is highly appreciated...
I decided to spend sometime examining you question. What I found out is that, I don't think you'd need to return the resized image through imagejpeg() the way you did. You might also need to add a imagedestroy(), after you call imagejpeg() in you function, to destroy the temporary memory used.
You need to first fully Upload the Image before resizing it. If you'd like, you could send the image in a temporary storage while you do whatever you want to it so that Php does not have to deal with it in a 'tmp_name' format...Then You can destroy the image later on.
Once the image is fully uploaded, things become easier. The codes might look something like:
if(isset($_FILES['images'])){
//may be some random numbers to accompany it.
$rand = floor((mt_rand()+rand()+mt_rand())/3);
//Send it to the temporary folder you have had to create.
if(move_uploaded_file(
$_FILES['images']['tmp_name'],'temporary_storage/image_'.$rand.'.jpg')){
//Then run the `resize` function from here.
$image_resized = resize_this_image_now('temporary_storage/image_'.$rand.'.jpg');
//Now You can get the size if you wish.
list($width,$height) = getimagesize('temporary_storage/image_'.$rand.'.jpg');
// Out put
echo "W:".$width."<br>H:".$height;
//After you use it as desired, you can now destroy it using unlink or so.
unlink('temporary_storage/image_'.$rand.'.jpg');
}else{
echo "Upload Error goes here";
}
}
Note this answer is produced after several trials and errors... Please use this strategy wisely.
Hope it helps.
A quick brief. We currently have to make small, medium and large images based on product images we have on our site. Not being a wiz on PHP I thought I would still try to automate this nightmare.
The image we upload and dimension of the thumb is below
800 width x 1400 width LARGE
300 width x 525 width THUMB
The problem with my PHP script is that it just resizes with scaling to proportion. I want to it to be able to scale down like in Photoshop, you just click shift and the image scales. I am trying to use imagecopyresized but with little luck.
<?php
// PHP UPLOAD SCRIPT
// VALIDATION OF FORM
if($_FILES['user_image']['type'] == "image/jpeg" && $_FILES['user_image']['size'] < 3000000)
{
// VARS
$target_folder = 'images/';
$upload_image = $target_folder.basename($_FILES['user_image']['name']);
// UPLOAD FUNCTION
if(move_uploaded_file($_FILES['user_image']['tmp_name'], $upload_image))
{
// VARS FOR FILE NAMES
$thumbnail = $target_folder."medium_x.jpg";
$actual = $target_folder."large_x.jpg";
// THUMBNAIL SIZE
list($width, $height) = getimagesize($upload_image);
$newwidth = "300";
$newheight = "525";
// VARS FOR CALL BACK
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($upload_image);
// RESIZE WITH PROPORTION LIKE PHOTOSHOP HOLDING SHIFT
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// MAKE NEW FILES
imagejpeg($thumb, $thumbnail, 100);
// FILE RENAMES
rename($upload_image, $actual);
{
// SUCCESS MESSAGES
?>
<p>
Image Successfully uploaded!<br />
Actual image: <?=$actual;?><br />
Thumbnail image: <?=$thumbnail;?><br />
<h1>Large</h1>
<img src="<?=$actual;?>"/><br /><br />
<h1>Medium</h1>
<img src="<?=$thumbnail;?>"/><br /><br />
</p>
<?
}
// FAILED MESSAGES
}
else
{
echo 'Upload failed.';
}
}
else
{
// NOT A JPEG
echo 'Not a JPEG';
}
// END OF SCRIPT
?>
How can I resize properly without having a stretched image? Is it possible?
The easiest way to achieve this without buckets of PHP code is with Image Magick. See examples and sample command line here: http://www.imagemagick.org/Usage/resize/#fill
(can call from PHP using exec() or similar)
Edit: Implementation as follows:
if($_FILES['user_image']['type'] == "image/jpeg" && $_FILES['user_image']['size'] < 3000000)
{
// VARS
$target_folder = 'images/';
$upload_image = $target_folder.basename($_FILES['user_image']['name']);
$thumbnail = $target_folder."medium_x.jpg";
$actual = $target_folder."large_x.jpg";
$newwidth = "300";
$newheight = "525";
if(move_uploaded_file($_FILES['user_image']['tmp_name'], $upload_image))
{
exec('convert '.$upload_image.' -resize '.$newwidth.'x'.$newheight.'^ '.$thumbnail);
rename($upload_image, $actual);
}
}
...
etc
You could optimise the way you handle the upload but I didn't want too totally change the structure of your code as I don't know what surrounds it. But basically, you push the image to ImageMagick's convert, and it will work it's magic.
If you want to crop as well as scale, the exec command would be:
exec('convert '.$upload_image.' -resize '.$newwidth.'x'.$newheight.'^ -gravity center -extent '.$newwidth.'x'.$newheight.' '.$thumbnail);
Look at this code snippet. Does what you need. Basically used to maintain ratio when creating the thumb.
http://snipplr.com/view/753/
I'm working on an image resizer, to create thumbnails for my page. The resizer works on principle of include a DIRECT link to the image. But what I want to do is put in the PHP Variable in the URL string, so that it points to that file and resizes it accordingly.
My code is as follows :
<img src="thumbnail.php?image=<?php echo $row_select_property['image_url']; ?>
Image Resize :
<?php
// Resize Image To A Thumbnail
// The file you are resizing
$image = '$_GET[image_url]';
//This will set our output to 45% of the original size
$size = 0.45;
// This sets it to a .jpg, but you can change this to png or gif
header('Content-type: image/jpeg');
// Setting the resize parameters
list($width, $height) = getimagesize($image);
$modwidth = $width * $size;
$modheight = $height * $size;
// Creating the Canvas
$tn= imagecreatetruecolor($modwidth, $modheight);
$source = imagecreatefromjpeg($image);
// Resizing our image to fit the canvas
imagecopyresized($tn, $source, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
// Outputs a jpg image, you could change this to gif or png if needed
imagejpeg($tn);
?>
What I am trying to do is pass on the variable "image=" to the Thumbnail script. At the moment I am passing it through the URL string, but it doesnt seem to load the graphic.
I'll try expand on this more, should you have questions as I am finding it a little difficult to explain.
Thanks in advance.
I suspect at least part of the problem is that your existing...
$image = '$_GET[image_url]';
...line is creating a text string, rather than getting the contents of the 'image_url' query string. Additionally, your passing in the image name as "?image=" in the query string, so you should simply use "image", not "image_url".
As such, changing this to...
$image = $_GET['image'];
...should at least move things along.
Change it
$image = '$_GET[image_url]';
to
$image = $_GET['image'];
$image = '$_GET[image_url]';
should be
$image = $_GET['image'];