PHPQuery - getting the image width and height - php

I am parsing a page using PHPQuery.
At some point I have obtained all images on the page using:
$url = "http://mywebsite.com";
$all = phpQuery::newDocumentFileHTML($url, $charset = 'utf-8');
// list of all images
$imgsrc = $all->find('img');
now I am interacting this list
foreach ($imgsrc as $img) {
$width = need magic command to extract image width
$height = need magic command to extract image height
}
The problem is this. The img attribute does not have a width or a height attribute but its class has.
The image tag is like this:
<img src="img1.png" class="alfa">
I need to get the width and height defined by that class.
I can get the class name by doing
$className = pq($img)->attr('class');
How do I do obtain the width/height of that class now?

list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
to get the image height and width.

Related

PHP imagecopymerge() - one image is stretched

I'm am trying to add a 50px white margin down the right side of an image by creating an empty image that's 50px wider than the source image and then merging the source image onto it. The problem is that the source image just gets stretched sideways so it's 50px wider!
Maybe I'm using the wrong function to merge the images ...
here's my code
$destImage = $filepath;
#echo "dest image = ".$destImage;
$sourceImage = imagecreatefrompng($filepath);
// dimensions
$src_wide = imagesx($sourceImage);
echo "src_wide=".$src_wide;
$src_high = imagesy($sourceImage);
// new image dimensions with right padding
$dst_wide = $src_wide+50;
echo "dst_wide=".$dst_wide;
$dst_high = $src_high;
// New resource image at new size
$dst = imagecreatetruecolor($dst_wide, $dst_high);
// set white padding color
$clear = array('red'=>255,'green'=>255,'blue'=>255);
// fill the image with the white padding color
$clear = imagecolorallocate( $dst, $clear["red"], $clear["green"], $clear["blue"]);
imagefill($dst, 0, 0, $clear);
// copy the original image on top of the new one
imagecopymerge($dst,$sourceImage,0,0,0,0,$src_wide,$src_high, 100);
imagepng($dst,$destImage,6);
imagedestroy($dst);
chmod($destImage,0775);
what am I doing wrong here ??
thanks
It's stretching because you are copying it to the full width of the destination image. Instead use
imagecopyresampled($dst,$sourceImage,50,0,0,0,$src_wide,$src_high,$src_wide,$src_high);

How to resize and display an image from url?

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",
});

image alpha channel extraction

Is it possibe to extract the alpha channel of an image and save it as a black and white png using the imagine php library?
I've been looking around but can't seem to find a way to do it.
Currently the code looks like this:
private function generateMask($file, $imagine){
$image = $imagine->open($file->getRealPath());
$image = $image->resize(new Imagine\Image\Box(200, 200));
$mask = $image->mask(); //Creates alpha from grayscale version instead of alpha
$newImage = $imagine->create(new Imagine\Image\Box(200, 200));
$newImage->applyMask($mask);
return $newImage;
}

set image width with php?

I am creating a custom blog with php. when the user is uploading an article I am having problem with the images in the post. some images's width are bigger than the main div in my blog (740). I want to use php to check the width of the images if it is bigger than 740 then re-size the image to 740.
<?php
$dom = new domDocument;
$dom->loadHTML($article_content);
$dom->preserveWhiteSpace = false;
$imgs = $dom->getElementsByTagName("img");
$links = array();
for($i=0;$i<$imgs->length;$i++){
$links[] = $imgs->item($i)->getAttribute("width");
$image_path = $links[];
$article_source = imagecreatefromstring(file_get_contents($image_path));
$image_width = imagesx($image_source);
if($image_width > 740){$image_width = 740;}
}
?>
so far this is the code that I have. I am not sure how to set the image width.(the image already has its original width)
UPDATE:
I am not trying to save or copy the image. I am trying to access the dom by php and set the image width to $image_width (of all images)
From your code I assume that you are using the GD library. In that case, what you are looking for is imagecopyresized().
Here's an example of what you might want if the image width is too great:
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($small_image, $image_source,
0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
Then $small_image will contained the scaled version of the image.
Without saving/copying the image you will have to replace img tags in the HTML document with ones having a width attribute.
$dom = new domDocument;
$dom->loadHTML($article_content);
$imgElements = $dom->getElementsByTagName("img");
foreach ($imgElements as $imgElement) {
$imgSrc = imagecreatefromstring(file_get_contents($imgElement->getAttribute("src")));
if (imagesx($imgSrc) > 740) {
// we replace the img tag with a new img having the desired width
$newE = $dom->createElement('img');
$newE->setAttribute('width', 740);
$newE->setAttribute('src', $imgElement->getAttribute("src"));
// replace the original img tag
$imgElement->parentNode->replaceChild($newE, $imgElement);
}
}
// html with "resized" images
echo $dom->saveHTML();

Passing an Variable from one PHP File to another

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'];

Categories