set image width with php? - 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();

Related

Using Imagick-resizeImage to create thumbnails creates dark images - PHP

I am able to successfully resize (to the proper resized dimensions) an image that I have created from one page of a pdf document. However, I do not understand why the result is a dark resized image with a patch of white. Please, can someone advise?
PHP code:
// Create image from first page of pdf document
$im = new imagick('1Mpublic.pdf[0]');
$im->setImageFormat('jpg');
$imageHeight = $im -> getImageHeight();
$imageWidth = $im -> getImageWidth();
$desiredImgWidth = 200;
$desiredImgHeight = resizedImageHeight($imageWidth, $imageHeight,
$desiredImgWidth);
$im -> resizeImage($desiredImgWidth, $desiredImgHeight,
imagick::STYLE_NORMAL, 1);
// Save image
$page = '1';
$saveToFolder = 'thumbnailFolder';
$fileName = 'thanhThumbNail_'.$page.'.jpg';
$saveImgToPath = $saveToFolder.'/'.$fileName;
$result = file_put_contents($saveImgToPath, $im);
function resizedImageHeight($imgWidth, $imgHeight, $desiredImgWidth){
$quoient = $imgWidth/$imgHeight;
$height = $desiredImgWidth/$quoient;
return $height;
}
Resulting thumbnail image:
Link to original PDF can be found here:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4905263/pdf/ksgt-06-04-1091539.pdf
Your PDF has transparency. JPG does not support transparency and shows black where the PDF was transparent. Just turn the transparency off. In Imagemagick command line:
convert -density 300 ksgt-06-04-1091539.pdf[0] -alpha off result.jpg
See setImageAlphaChannel at http://us3.php.net/manual/en/imagick.setimagealphachannel.php
Looks like the background color is not defined. You need to set the background color before reading the PDF document.
// Create image from first page of pdf document
$im = new imagick();
$im->setBackgroundColor('WHITE');
$im->readImage('1Mpublic.pdf[0]');
$im->setImageFormat('jpg');

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 set x and y coordinates in image manipulation.

i just do image watermarking in php it's working but not setting image like i want,here's my code of php file.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
if(isset($_POST['submit']))
{
// Give the Complete Path of the folder where you want to save the image
$folder="uploads/";
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "$folder".$_FILES["fileToUpload"]["name"]);
$file='uploads/'.$_FILES["fileToUpload"]["name"];
$uploadimage=$folder.$_FILES["fileToUpload"]["name"];
$newname=$_FILES["fileToUpload"]["name"];
// Set the thumbnail name
$thumbnail = $folder.$newname."_thumbnail.jpg";
$actual = $folder.$newname.".jpg";
$imgname=$newname."_thumbnail.jpg";
// Load the mian image
$source = imagecreatefromjpeg($uploadimage);
// load the image you want to you want to be watermarked
$watermark = imagecreatefrompng('uploads/logo1.png');
// get the width and height of the watermark image
$water_width = imagesx($watermark);
$water_height = imagesy($watermark);
// get the width and height of the main image image
$main_width = imagesx($source);
$main_height = imagesy($source);
// Set the dimension of the area you want to place your watermark we use 0
// from x-axis and 0 from y-axis
$dime_x = 0;
$dime_y = 0;
// copy both the images
imagecopy($source, $watermark, $dime_x, $dime_y, 0, 0, $water_width, $water_height);
// Final processing Creating The Image
imagejpeg($source, $thumbnail, 100);
}
?>
<img src='uploads/<?php echo $imgname;?>'>
</body>
</html>
and my html code also working fine.but problem with generated image it's like that
text with 'JACLIN ADMIN' is my png image and i want to apply it in middle from up and left. i just put 0 for both but problem is how can i put it in middle dynamicaly when size of images with diffrent height and width?please help me.
First, you need to find the middle point of your image:
$im_middle_w = $main_width/2;
$im_middle_h = $main_height/2;
Then you just need to add the watermark there but you need to move the watermark to the left by half (so it's actually centered):
$dime_x = $im_middle_w - $water_width/2;
$dime_y = $im_middle_h - $water_height/2;
Haven't tested it but it should work. If it doesn't work, feel free to link the images and I'll see to the code myself.
First set Value:
$watermark_pos_x = (imagesx($image)/2) - (imagesx($watermark)/2) - 15; $watermark_pos_y = (imagesy($image)/2) - (imagesy($watermark)/2) - 10;
Then after apply value on Function:
// merge the source image and the watermark
imagecopy($image, $watermark, $watermark_pos_x, $watermark_pos_y, 0, 0, imagesx($watermark), imagesy($watermark));

PHPQuery - getting the image width and height

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.

PHP Thumbnail from image from url

I'm using the code, that first checks filenames in folder and then creates url. In the url find it the special line where is an imagefile. It displays correctly image and address, but if images are too big, takes it so long time. Is it possible to create thumbnail and display this instead of image? Thank You!
require_once('simple_html_dom.php');
$files = scandir('files/');
foreach($files as $file) {
if($file == '.' || $file == '..') continue;
$file = basename($file, ".html");
$url = 'http://address.com/test/'.$file;
$html = file_get_html($url);
foreach($html->find('img') as $element) {
if (strpos($element,'address.com') !== false) {
$url = $element->src;
echo $url.'</br>';
echo '<IMG SRC="',$url, '" WIDTH="128" HEIGHT="96" BORDER="0" ALT="" /><br/>';
}
}
}
You want to use CSS clip:rect(50px 218px 155px 82px);
Setting width and height does not decress the ACTUAL image size, so load time will still take just as long. See this article on step by step div creation and css coding.
http://www.seifi.org/css/creating-thumbnails-using-the-css-clip-property.html
Also as a side note, nothing beats ACTUALLY MAKING TUMBNAILS! There are serve side thumbnail generators, but this is the best you'll get with out actually making tumbnails.
I wrote a blog post on How to proportionally resize uploaded images, you should be able to adjust the code from the sample I wrote to do what you want.
Pasting the code below in case my site dies in the future.
<?php
// *snip* Removed form stuff
$image = imagecreatefromjpeg($pathToImage);
// Target dimensions
$max_width = 240;
$max_height = 180;
// Calculate new dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
$scale = min($max_width/$old_width, $max_height/$old_height);
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resample old into new
imagecopyresampled($new, $image,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);
// Catch the image data
ob_start();
imagejpeg($new, NULL, 90);
$data = ob_get_clean();
// Destroy resources
imagedestroy($image);
imagedestroy($new);
// Output image data
header("Content-type: image/jpeg", true, 200);
echo $data;
You'd probably want to stick this in a function and change it output to a file. Then generate the thumbnail in your foreach loop and link to the thumbnail instead of the original. You should also check if you have already created a thumbnail for an image so you don't do it more than once for each image.

Categories