【问题标题】:Finding the coordinates of an image in every HTML file in a directory?在目录中的每个 HTML 文件中查找图像的坐标?
【发布时间】:2013-03-06 21:04:37
【问题描述】:

我有一个带有类似图像标签的平面 HTML 文件库。我应该如何遍历所有这些并在特定图像标签的页面上找到特定的x,y坐标?

我认为我需要将每个页面呈现为图像(将我正在寻找的图像标签替换为我可以匹配的特定颜色)或者我可以无头呈现页面使用 phantom.js 之类的东西并以这种方式找到坐标(尽管我不知道这是否可行)。有什么想法会更容易吗?

我更喜欢使用 LAMP 堆栈或 Node.js。

谢谢!

【问题讨论】:

  • “坐标”是什么意思?你是说图片大小吗?
  • 例如,图像是否一直位于左上角? (x = 0, y = 0) 或中间某处 (x = 555, y = 424)。我需要知道图像相对于页面其余部分的 x、y 坐标。

标签: node.js zend-framework imagemagick lamp


【解决方案1】:

我认为使用 PhantomJS 将是最简单的。不需要 node.js。

你可以结合examples/scandir.jsexamples/phantomwebintro.js来得到你想要的。

var system = require('system');
var fs = require('fs');

if (system.args.length !== 2) {
    console.log("Usage: phantomjs scandir.js DIRECTORY_TO_SCAN");
    phantom.exit(1);
}

function scanDirectory(path, cb) {
    if (fs.exists(path) && fs.isFile(path)) {
        cb(path);
    } else if (fs.isDirectory(path)) {
        fs.list(path).forEach(function (e) {
            if (e !== "." && e !== "..") {
                scanDirectory(path + '/' + e, cb);
            }
        });
    }
}

function parsePage(path) {
    var page = require('webpage').create();
    page.open(path, function(status) {
        if (status === "success") {
           page.includeJs("http://code.jquery.com/jquery-latest.js", function() {
               var images = page.evaluate(function() {
                    var images = [];
                    $('img').each(function() {
                        images.push({ src: $(this).attr('src'), pos: $(this).position() });
                    });
                    return images;
               });
               console.log(images);
           });
         }
    });
}

scanDirectory(system.args[1], parsePage);

此脚本 (phantomjs img.js kittens) 将扫描目录中的文件,加载该目录(和子目录,您可以在 scanDirectory 中修改此行为)中的每个文件,并在该页面上找到所有 <img> 标签并返回一个具有src 属性和.position() 的数组。

我花了大约 20 分钟才完成这项工作,所以我认为这是最简单的方法。

【讨论】:

    猜你喜欢
    • 2018-04-01
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多