草庐IT

go - 将多个文件传递给存储桶中的 exec.Command 调用

coder 2024-07-06 原文

我正在尝试构建一个用 Go 编写的云函数,它将使用 Google 的 Cloud Functions 基础架构中可用的 ImageMagick 库来将多个图像合成并处理成最终的输出图像。

问题的根源是我想使用的 ImageMagick 函数可用,但它需要多个不同的输入才能工作。我的输入是存储桶中的对象。

os/exec Cmd 结构允许您通过使用“ExtraFiles”数组来执行此操作,而且我知道如何将这些额外文件提供给我的 ImageMagick 命令。

但是,“ExtraFiles”数组只想存储 os.File 的实例,而 GCP Storage Client 在您打开文件时会为您提供一个“Reader”实例。

        backgroundBlob := storageClient.Bucket(inputBucket).Object(background)
        backgroundImg, err := backgroundBlob.NewReader(ctx)
        if err != nil {
                return "", fmt.Errorf("backgroundImg: %v", err)
        }

        foregroundBlob := storageClient.Bucket(inputBucket).Object(foreground)
        foregroundImg, err := foregroundBlob.NewReader(ctx)
        if err != nil {
                return "", fmt.Errorf("foregroundImg: %v", err)
        }

        outputBlob := storageClient.Bucket(outputBucket).Object(output)
        outputImg := outputBlob.NewWriter(ctx)
        defer outputImg.Close()

        // Set up some additional file handles since we're dealing with more inputs than STDIN Can cope with
        cmd := exec.Command("convert", "fd:3", "fd:4", "-composite", "fd:5")
        cmd.ExtraFiles = append(cmd.ExtraFiles,backgroundImg)
        cmd.ExtraFiles = append(cmd.ExtraFiles,foregroundImg)
        cmd.ExtraFiles = append(cmd.ExtraFiles,outputImg)

        if err := cmd.Run(); err != nil {
                return "", fmt.Errorf("cmd.Run: %v", err)
        }

        log.Printf("Blurred image has been uploaded to %s", outputBlob.ObjectName())

        return outputBlob.ObjectName(), nil
}```

So, from where I am at the moment, I need to do one of the following two things:
1. Figure out how to get Google's storage API to treat/use objects in their storage buckets as "os.File"s
OR
2. Figure out how to execute my "convert" command using multiple Readers as input, rather than leveraging the ExtraFiles array.

If anybody out there has any ideas on how to achieve either of the above, or has alternate ways of solving this problem, I would be very grateful to hear them!

最佳答案

对于以后遇到这个问题的任何人 - 我找到了解决方法。我对它并不满意,但它很实用。

基本上,我能够读取存储读取器的内容,然后在 Cloud Functions 上下文中创建我自己的 os.File 对象。然后,将该 os.File 传递给 exec.Cmd 调用。这绝对不理想,但这是代码:

func Overlay(ctx context.Context, inputBucket, outputBucket, background string, foreground string, output string) (string, error) {
        // Retrieve the Background Image from the storage API
        backgroundBlob := storageClient.Bucket(inputBucket).Object(background)
        backgroundImg, err := backgroundBlob.NewReader(ctx)
        if err != nil {
                return "", fmt.Errorf("backgroundImg: %v", err)
        }        
        // Read the contents of the file into a variable
        backgroundSlurp, err := ioutil.ReadAll(backgroundImg)
        if err != nil {
                return "", fmt.Errorf("readFile: unable to read data from bucket %q, file %q: %v", inputBucket, background, err)
        }
        // Write the contents of Background Image to an os.File instance
        err = ioutil.WriteFile(fmt.Sprintf("/tmp/%s",background), backgroundSlurp, 0644)
        if err != nil {
                return "", fmt.Errorf("backgroundImg: %v", err)
        }
        // Open the os.File instance to pass it on to os.exec later
        backgroundFile, err := os.Open(fmt.Sprintf("/tmp/%s",background))
        if err != nil {
                return "", fmt.Errorf("backgroundFile: %v", err)
        }

        foregroundBlob := storageClient.Bucket(inputBucket).Object(foreground)
        foregroundImg, err := foregroundBlob.NewReader(ctx)
        if err != nil {
                return "", fmt.Errorf("foregroundImg: %v", err)
        }
        // Read the contents of the file into a variable
        foreroundSlurp, err := ioutil.ReadAll(foregroundImg)
        if err != nil {
                return "", fmt.Errorf("readFile: unable to read data from bucket %q, file %q: %v", inputBucket, foreground, err)
        }
        // Write the contents of Foreground Image to an os.File instance
        err = ioutil.WriteFile(fmt.Sprintf("/tmp/%s",foreground), foreroundSlurp, 0644)
        if err != nil {
                return "", fmt.Errorf("foregroundImg: %v", err)
        }
        // Open the os.File instance to pass it on to os.exec later
        foregroundFile, err := os.Open(fmt.Sprintf("/tmp/%s",foreground))
        if err != nil {
                return "", fmt.Errorf("foregroundFile: %v", err)
        }

        outputBlob := storageClient.Bucket(outputBucket).Object(output)
        outputImg := outputBlob.NewWriter(ctx)
        defer outputImg.Close()

        // Set up some additional file handles since we're delaqing with more inputs than STDIN Can cope with
        cmd := exec.Command("convert", "fd:3", "fd:4", "-composite", "-")
        cmd.Stdout = outputImg
        cmd.ExtraFiles = append(cmd.ExtraFiles,backgroundFile)
        cmd.ExtraFiles = append(cmd.ExtraFiles,foregroundFile)

        if err := cmd.Run(); err != nil {
                return "", fmt.Errorf("cmd.Run: %v", err)
        }

        log.Printf("Blurred image has been uploaded to %s", outputBlob.ObjectName())

        return outputBlob.ObjectName(), nil
}

关于go - 将多个文件传递给存储桶中的 exec.Command 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57077072/

有关go - 将多个文件传递给存储桶中的 exec.Command 调用的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  4. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  5. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  6. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  7. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  8. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  9. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  10. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

随机推荐