首页 > 解决方案 > 我需要知道如何将 Windows 10 PC 上的文件中的图像添加到谷歌应用脚​​本 HTML 网站

问题描述

我想将图像添加到谷歌应用脚​​本托管网页。

我试着环顾菜单并检查谷歌。

我希望它以所需的大小显示图像

标签: imagegoogle-apps-script

解决方案


Web 应用程序中我的 Google 照片库中的相册中的图像

function doGet(e){
  return displayAlbums(true);
}

//used for web app and dialog depending upon weather web parameter is true or not.  If it's not provided then it's false. 
function displayAlbums(web) {
  var web=web||false;
  //different color backgrounds for each album
  var bgA=['#f3eeb3','#f3e2b3','#f3ceb3','#f3b3b6','#f3b3b6','#f3b3ef','#b3eaf3','#b3f3e3','#b3f3cb','#bdf3b3']
  var html='';
  var n=0;
  var albumsA=listAlbums();
  for(var i=0;i<albumsA.length;i++) {
    html+='<html><head></head><body>';
    html+=Utilities.formatString('<div id="d-%s" style="margin:auto;max-width:500px;background-color:%s;">',i,bgA[i]);
    html+=Utilities.formatString('<h1>%s</h1>', albumsA[i].title);
    var images=listImagesOfAnAlbum(albumsA[i].id);
    for(var j=0;j<images.length;j++) {
      html+=Utilities.formatString('<br />%s - %s<br /><img src="%s" width="500" />',j+1,images[j].filename, images[j].baseUrl);
    }
    html+='</div></body></html>';
  }
  if(!web) {
    var userInterface=HtmlService.createHtmlOutput(html).setWidth(600).setHeight(500);
    SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Displaying my Albums');
  }else{
    var output=HtmlService.createHtmlOutput(html).setWidth(600).setHeight(500);
    return output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).addMetaTag('viewport', 'width=360, initial-scale=1');
  }
}

function listAlbums() {
  var token=null;
  var fA=[];
  var n=0;
  do{
    var params = {muteHttpExceptions:true,headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}};
    var url=Utilities.formatString('https://photoslibrary.googleapis.com/v1/albums?pageSize=50%s',(token!=null)?"&pageToken=" + token:"");
    var resp=UrlFetchApp.fetch(url,params);
    var js=JSON.parse(resp.getContentText());
    for(var i=0;i<js.albums.length;i++) {
      fA.push({id:js.albums[i].id,title:js.albums[i].title,count:js.albums.mediaItemsCount});
    }
    token=js.nextPageToken;
  }while(token!=null);
  Logger.log(fA);
  return fA;
}

function listImagesOfAnAlbum(albumId) {
  var albumId= albumId || 'Default Id for debugging';
  var token=null;
  var iA=[];
  var n=0;
  do{
    var params = {
      method:"post",
      muteHttpExceptions:true,
      headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
      payload:{"albumId": albumId,"pageSize":"50","pageToken":token}};
    var url="https://photoslibrary.googleapis.com/v1/mediaItems:search";
    var resp=UrlFetchApp.fetch(url,params);
    var js=JSON.parse(resp.getContentText());
    for(var i=0;i<js.mediaItems.length;i++) {
      iA.push({filename:js.mediaItems[i].filename,baseUrl:js.mediaItems[i].baseUrl});
    }
    token=js.nextPageToken;
  }while(token!=null);
  return iA;
}

谷歌相册 API

我将此添加到清单文件中:

"exceptionLogging": "STACKDRIVER",
  "oauthScopes": ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/photoslibrary", "https://www.googleapis.com/auth/script.container.ui", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/script.scriptapp", "https://www.googleapis.com/auth/spreadsheets"]

即使您不需要它也将其添加到您的谷歌脚本中,这会激发身份验证器添加需要的范围。并且还在 Resources Advanced Google Services 中设置 Drive API。

//DriveApp.getFiles();
function listFiles() {
  var files = Drive.Files.list({
    fields: 'nextPageToken, items(id, title)',
    maxResults: 10
  }).items;
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    Logger.log('\n%s-Title: %s Id: %s',i+1,file.title,file.id);
  }
}

这是 Bruce McPherson 将其描述为借用令牌的技术,您可以在此处阅读有关它的信息

我已经加载了 Oauth2 和 GOA 库。根据 McPherson 先生,您将需要安装 GOA 库,尽管我从未积极使用过它。他在这里散步只需浏览他的小幻灯片演示。这可能看起来很麻烦,而且确实如此。但它确实为您提供了对照片库的编程访问。幸运的是,谷歌在我们的大部分图书馆都为我们做了这一切。

使用 DataURI 从您的个人计算机到您的网站

另一种将图像从您的 Google Drive 中获取并进入您的 webapp 网站的方法。

在此处输入图像描述

<script>您网站标签中的 Javascript :

         google.script.run
         .withSuccessHandler(function(iObj){
           console.log(iObj);
           for(var i=0;i<iObj.iA.length;i++) {
             if(i==iObj.iA.length-1) {
               $('#header').css('background-image','URL(' + iObj[iObj.iA[i]] + ')');
             }else{
               $('#' + iObj.iA[i]).attr('src',iObj[iObj.iA[i]]);
             }
           }
         })
         .getSimpleSiteImages();
        });

Google Apps 脚本:

function getSimpleSiteImages() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('SimpleSite');
  var rg=sh.getDataRange();
  var vA=rg.getValues();
  var oObj={iA:[]};
  for(var i=0;i<vA.length;i++) {
    oObj.iA[i]=vA[i][2];
    oObj[oObj.iA[i]]=getDataURI(vA[i][1]);
  }
  return oObj;
}

function getDataURI(fileId) {
  var file=DriveApp.getFileById(fileId);
  return file.getBlob().getDataAsString();
}

生成 DataURI 的 Google Apps 脚本:

function convImageUrl(url){
  var blob=UrlFetchApp.fetch(url).getBlob();
  var b64Url='data:' + blob.getContentType() + ';base64,' + Utilities.base64Encode(blob.getBytes());
  return b64Url;
}

只需保存在您的谷歌驱动器上并将它们上传到您的图像中。


推荐阅读