使用php设置图像宽度


set image width with php?

我正在用php创建一个自定义博客。当用户上传文章时,我对帖子中的图像有问题。有些图片的宽度比我博客中的主div大(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_width(所有图像的)

根据您的代码,我假设您正在使用GD库。在这种情况下,您要查找的是imagecopyresized()。

如果图像宽度太大,您可能需要以下示例:

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

$small_image将包含图像的缩放版本。

如果不保存/复制图像,您将不得不用具有width属性的标签替换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();