user1481850
user1481850

Reputation: 248

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)

Upvotes: 1

Views: 3245

Answers (2)

Czar Pino
Czar Pino

Reputation: 6314

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();

Upvotes: 1

Andrew
Andrew

Reputation: 2154

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.

Upvotes: 2

Related Questions