我正在用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(所有图像)
答案 0 :(得分:2)
从您的代码中我假设您正在使用GD库。在这种情况下,您要找的是imagecopyresized()。
以下是图像宽度过大时可能需要的示例:
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($small_image, $image_source,
0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
然后$small_image
将包含图像的缩放版本。
答案 1 :(得分:1)
如果不保存/复制图像,则必须将HTML文档中的img标记替换为具有width属性的标记。
$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();