使用 domcrawler (Goutte) 获取抓取图像的大小

菲利克斯·马克西姆

对于我的网站,用户可以提交链接。

我想要的是,当一个链接被提交时,它解析被链接页面的 DOM,找到最大的图像(最大的是总宽度 + 总高度),并保存该页面上最大图像的缩略图。

这样缩略图就可以在他们的链接旁边。

为了实现这一点,我在 Laravel 中使用了 Goutte 包和 Image Intervention 包。

这是我到目前为止所做的:

$goutteClient = new Client();
$guzzleClient = new GuzzleClient(array(
    'timeout' => 15,
));
$goutteClient->setClient($guzzleClient);

$crawler = $goutteClient->request('GET', 'https://www.reddit.com');

$result = $crawler
->filterXpath('//img')
->extract(array('src'));

foreach ($result as $image) {
    //get the width and height of each $image
}       

//$file = image with the biggest width + height


$thumbnail = Image::make($file);
$large->resize(900, 900, function ($constraint) {
    $constraint->aspectRatio();
    $constraint->upsize();
});     

注释掉的部分是我正在努力解决的问题。

foreach将返回src的形象,但我不知道如何查看图像的属性。

做这个的最好方式是什么?保存页面上的所有图像然后查看它们的宽度/高度对我来说不是一个选择。

麦威逊

我相信你可以使用,

getimagesize()

https://www.php.net/manual/en/function.getimagesize.php

它将返回您正在寻找的属性数组。包括高度和宽度。它要求在您的服务器配置中将 allow_url_fopen 设置为 true。假设图像是远程的。

所以在你的情况下。它可能看起来像……

    $files = [];

// maybe pass this by reference as &$image and store the totals in the same array, otherwise
foreach ($images as $image) {
    $attributes = getimagesize($image);

    $height = $attributes[0];
    $width = $attributes[1];

    $total = $height + $width;

    // bind the total as the id of the array, if there are multiple matching totals, it will always be the last
    // image that matches that is selected.
    $files[$total] = $image;
}

// then you can use any standard logic to extract the data from the new array.

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

是否可以使用Goutte解析JSON?

来自分类Dev

使用golang获取图像大小

来自分类Dev

如何将Symfony DomCrawler与Laravel的子域路由一起使用?

来自分类Dev

在Symfony 2+中使用Goutte进行过滤

来自分类Dev

Symfony DomCrawler

来自分类Dev

使用Goutte和PHP抓取列表以获取href的问题

来自分类Dev

如何使用Goutte Crawler提取数据?

来自分类Dev

如何在Goutte中下载图像

来自分类Dev

使用Symfony DomCrawler获取表行

来自分类Dev

如何使用Goutte抓取laravel 5.2?

来自分类Dev

使用Goutte顺序刮取图像,链接和文本

来自分类Dev

如何在Laravel中使用Goutte解析HTML时获取最后一个孩子

来自分类Dev

使用goutte从链接返回空值

来自分类Dev

Goutte-从$ crawler-> filter()获取内部值

来自分类Dev

用Goutte和Guzzle进行网页抓取

来自分类Dev

是否可以使用Goutte解析JSON?

来自分类Dev

使用ajax上传后获取图像大小

来自分类Dev

在Symfony 2+中使用Goutte进行过滤

来自分类Dev

使用symfony domcrawler获取选择选项值的列表

来自分类Dev

使用DomCrawler检查表行

来自分类Dev

如何在Goutte中下载图像

来自分类Dev

在Symfony的domCrawler组件中使用HTTP代理

来自分类Dev

如何使用Symfony \ DomCrawler以非格式分配textarea值?

来自分类Dev

如何使用Goutte获取div标签中存在的所有链接

来自分类Dev

如何使用Goutte登录到Amazon SellerCentral

来自分类Dev

如何为 domCrawler symfony 使用通配符?

来自分类Dev

PHP Goutte 网页抓取

来自分类Dev

Goutte - 在迭代列时从 td 获取链接

来自分类Dev

Goutte Crawler 无法获取某些类名值