用php设置图像宽度?

用php设置图像宽度?,php,Php,我正在用php创建一个自定义博客。当用户上传文章时,我对文章中的图片有问题。有些图片的宽度比我博客中的主分区(740)大。我想使用php来检查图像的宽度,如果它大于740,那么将图像的大小重新调整为740 <?php $dom = new domDocument; $dom->loadHTML($article_content); $dom->preserveWhiteSpace = false; $imgs = $dom->getElementsByTagName("

我正在用php创建一个自定义博客。当用户上传文章时,我对文章中的图片有问题。有些图片的宽度比我博客中的主分区(740)大。我想使用php来检查图像的宽度,如果它大于740,那么将图像的大小重新调整为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;}      
}   

?>

到目前为止,这是我的代码。我不确定如何设置图像宽度。(图像已具有其原始宽度) 更新:
我没有试图保存或复制图像。我试图通过php访问dom,并从代码中将图像宽度设置为$image\u width(所有图像)

,我假设您使用的是GD库。在这种情况下,您要寻找的是

下面是一个示例,说明如果图像宽度太大,您可能需要什么:

$thumb = imagecreatetruecolor($newwidth, $newheight);

imagecopyresized($small_image, $image_source,
        0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);

然后,
$small\u image
将包含图像的缩放版本。

如果不保存/复制图像,则必须将HTML文档中的img标记替换为具有宽度属性的标记

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

这行不行吗<代码>如果($image\u width>740){$image\u width=740;}
$imgs->item($i)->setAttribute(“width”,$image\u width)?@paul这是设置图像的宽度。但是它没有设置实际的图像宽度。@Rocket应该是
width
而不是
src
我没有试图保存或复制图像。我正在尝试通过php访问dom,并将图像宽度设置为$image_width,在这种情况下@Rocket的注释应该是您所需要的。