Search code examples
google-apps-scriptgoogle-drive-apigoogle-photosgoogle-photos-api

Google Apps Scripts: import (upload) media from Google Drive to Google Photos?


I see that we can import (upload) media (photos, videos,...) from Google Drive to Google Photos. My goal is: do this task with code.

I have successfully got a list of photos from Google Drive, and I store their IDs in an Array. I have this code:

  var arrId =
  [
   //Some image id...
  ]; 
  var length = arrId.length;
  var driveApplication = DriveApp;
  for(var i=0;i<length;++i)
  {
    var file = driveApplication.getFileById(arrId[i]);
    //Now I got the file, how can I programmatically import this file to Google Photos
  }

I have searched the docs of Google Script, but I couldn't find any API of Google Photos.

Thanks.


Solution

    • You want to upload an image file in Google Drive to Google Photo.
    • You want to achieve this using Google Apps Script.

    If my understanding is correct, how about this answer?

    In this answer, I would like to achieve your goal using a Google Apps Script library of GPhotoApp. This library has the method for uploading a file in Google Drive to Google Photo.

    Usage:

    1. Linking Cloud Platform Project to Google Apps Script Project:

    About this, you can see the detail flow at here.

    2. Install library

    Install this library.

    • Library's project key is 1lGrUiaweQjQwVV_QwWuJDJVbCuY2T0BfVphw6VmT85s9LJFntav1wzs9.
    IMPORTANT

    This library uses V8 runtime. So please enable V8 at the script editor.

    About scopes

    This library use the following 2 scopes. In this case, when the library is installed, these scopes are automatically installed.

    • https://www.googleapis.com/auth/photoslibrary
    • https://www.googleapis.com/auth/script.external_request

    Sample script 1:

    At first, please retrieve the album ID you want to upload. For this, please use the following script.

    function getAlbumList() {
      const excludeNonAppCreatedData = true;
      const res = GPhotoApp.getAlbumList(excludeNonAppCreatedData);
      console.log(res.map(e => ({title: e.title, id: e.id})))
    }
    

    Sample script 2:

    Using the retrieved album ID, you can upload the image files to Google Photo. In this sample script, arrId of your script is used.

    function uploadMediaItems() {
      const albumId = "###";  // Please set the album ID.
      var arrId =
      [
       //Some image id...
      ]; 
    
      const items = arrId.map(id => {
        const file = DriveApp.getFileById(id);
        return {blob: file.getBlob(), filename: file.getName()};
      });
      const res = GPhotoApp.uploadMediaItems({albumId: albumId, items: items});
      console.log(res)
    }
    

    Note:

    • In my environment, I could confirm that the above scripts worked.

    References: