Search code examples
phplaravelgoogle-drive-api

How can I show images from a Google Drive folder?


I am building a testing website. In login confirmation, I have to show the examinee their pictures, which is already saved in Google Drive Folder.

$optParams = array(
            'pageSize' => 1,
            'fields' => 'nextPageToken, files(contentHints/thumbnail,fileExtension,id,name,size)',
            'q' =>"mimeType contains 'image/' AND name contains '".$imageId."' AND '".$folderIdId."' in parents"
          );
          $results = $googleDriveService->files->listFiles($optParams);
          
        if (count($results->getFiles()) == 0) {
            print "No files found.\n";
        } else {
            print "Files:\n";
            foreach ($results->getFiles() as $file) {
                printf("%s (%s)\n", $file->getName(), $file->getId());
            }
        }

This is what I used to get the file ID. Now in order to preview the image to the page, do I have to download the image (then delete it later) in order to show it, or is there another way to do it without downloading?


Solution

  • Answer:

    While Drive is not designed to be a hosting platform, you use the preview link as a workaround.

    More Information:

    I really should reiterate here: Drive is not designed to be an image hosting platform. It is a file sharing and cloud storage solution primarily, but does provide methods of viewing images via preview, view and embed links.

    You can use the following link, replacing [ID] with your image ID to embed or preview an image in a page:

    https://drive.google.com/uc?export=view&id=[ID]
    

    NB: While this works, the image will load slowly as image hosting is not the M.O. of Drive. There is also an iframe option provided in the form of an embed:

    <iframe src="https://drive.google.com/file/d/[ID]/preview" width="640" height="480"></iframe>
    

    This iframe embed is obtainable from the Drive UI:

    After double-clicking your image at drive.google.com, and following the ⋮ > Open in new window menu item, in the newly opened tab follow the ⋮ > Embed item... menu option and the iframe code will open in a modal.