从谷歌api图像获取base64

时间:2017-12-11 11:51:15

标签: image api google-api base64

我在我的网站上使用Google oAuth登录并从自己的谷歌硬盘分享一些照片。现在,谷歌检索了以下类似的链接:

https://doc-0o-30-docs.googleusercontent.com/docs/securesc/dpstkbb0rv4jmf62kb8dc9m8ijh53ocp/1hotfemebktd56o93gcoi76k89edbtjp/1512662400000/05170378500578169489/05170378500578169489/1MxIJ5EBLcIVtqxjGi_ZoYYqpw1UQHBiCRA?e=download&gd=true

我已将此网址更改为安全原因

问题是我想让这个图像的base64保存在与用户相关的特定文件夹中但由于某种原因。使用PHP函数file_get_contents();它不起作用。

我尝试使用JS canvas来获取img.toDataURL(),但它仍然失败。

有一些方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:1)

我使用 node.js 和npm package googleapis(来自Google的官方软件包)遇到了同样的问题。

虽然我迟到了,但它可能会帮助其他人寻找类似的问题。

<强> Node.js的

var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;

//setup your oauth credentials and tokens

oauth2Client.setCredentials(tokens);

var drive = google.drive({
    version: 'v2',
    auth: oauth2Client
});

drive.files.get({
    fileId: fileId, //id of the file you are looking for
    alt: 'media'
}, {
    responseType: 'arraybuffer',
    encoding: null
}, function(err, response) {
    if (err) {
        console.log(err);

        //handle the error
    } else {
        var imageType = response.headers['content-type'];
        var base64 = new Buffer(response.data, 'utf8').toString('base64');
        var dataURI = 'data:' + imageType + ';base64,' + base64;

        res.send(dataURI);
    }
});

<强> HTML

<img src="dataURI_received_from_above_HTTP_request"></img>

答案 1 :(得分:0)

我发现了问题。要使用google api获取内容,首先,我们应该设置正确的范围。在这种情况下,https://www.googleapis.com/auth/drive

所以,我们应该在get_file_contents()中设置使用access_token传递参数“Authorization”的上下文。所以,代码将是:

    $context = stream_context_create(array(
            'http' => array(
                'header'  => "Authorization: Bearer [ACCESS_TOKEN_HERE]"
            )
        ));

   $conteudo = file_get_contents($urlImagem, false, $context);

这是我的解决方案。我希望它可以帮助别人。

相关问题