Google Apps Script - get 'hosting' url for public image on Drive - image

and thanks in advance for your help!
I'm trying to get the 'hosting' URL for public images on my Google Drive, with the intent of pulling the images into a spreadsheet using the Image formula. Unfortunately, there doesn't seem to be a way to get the hosting URL from Google Apps Script.
The ID used in the hosting URL isn't the same as the ID of the file on Drive, either, so I can't figure out how to build the URL.
Is there a way to get this URL or ID so I can pull in these images to my spreadsheet?
Thanks again for any help you can provide.

Can the use of permalink be an option for you?
here an exemple:
var baseUrl = "http://drive.google.com/uc?export=view&id=";
function myFunction() {
var images = DriveApp.getFilesByType(MimeType.JPEG);
while(images.hasNext()){
var img = images.next();
// img.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW); this line can be dangerous!!
var imgId = img.getId();
var pubUrl = baseUrl+imgId; // the public URL
Logger.log(pubUrl);
}
}

Related

Setting link URL with Google Docs API doesn't result in update of image

I'm trying to update a placeholder image with a new image that has an updated URL. The URL in fact is a valid Google Static Map URL that I'm using in other contexts successfully. I'm using the Google Document API to manipulate the document. Following the code I've been using:
var element = body.findElement(DocumentApp.ElementType.INLINE_IMAGE).getElement();
var imageMap = element.asInlineImage();
// if there was an image found in document
if (imageMap != null) {
// get current parent and index inside parent
var parent = imageMap.getParent();
var childIndex = parent.getChildIndex(imageMap);
// remove image from paragraph
imageMap = imageMap.removeFromParent();
// get static image url for territory
var url = getStaticMapURLForTerritory(id);
Logger.log(url);
imageMap.setLinkUrl(url);
// create a new image
parent.insertInlineImage(childIndex, imageMap)
}
This seems to work fine in that it does update the image url correctly. However, the image itself (the result of the url) is not updated. When I click on the link URL it does return the correct image.
Is there a way to force a refetch of the image blob associated with the URL? I've also attempted to use UrlFetchApp but that complains about a missing size parameter (google static api) which is certainly included in the url string and within the max 640x640 bounds.
I've exhausted all my options unless....
TIA, --Paul
setLinkUrl only does that: sets the link. To actually add a new image you'll have to get its blob:
function replaceImage() {
// [...]
// get static image url for territory
const url = getStaticMapURLForTerritory(id)
const response = UrlFetchApp.fetch(url)
// create a new image
parent.insertInlineImage(childIndex, response.getBlob())
.setAltDescription(img.getAltDescription())
.setAltTitle(img.getAltTitle())
.setWidth(img.getWidth())
.setHeight(img.getHeight())
.setLinkUrl(url)
}
References
Class InlineImage (Google Apps Script reference)

How can i get the picture filename from a google drive url?

I have a lot of picture links in my Google Sheet:
https://drive.google.com/file/d/1BDj24_6uz-ZQlGWLy0o1_DES6tJI3NMu/view?usp=sharing
I want to get the filename behind the link. When i open the link and save the image the image filename is: "FILENAME.jpg" or something similar
I want to get this information in Sheets.
How can i do that?
An Apps Script Solution
Thanks to #Tanaike for obtaining clarifications in the comments.
First enter your links in the format shown below in a Google Sheet.
The name of the titles is not important, but this particular script starts getting names from the 2nd row.
If you don't know how to create a script, there are tutorials here offered by Google. You should create the script from the same Sheet. That is, from the menu in the Sheet:
In the script editor, copy and paste the following code:
function getNames() {
var activeRange = SpreadsheetApp.getActiveSheet().getDataRange();
var height = activeRange.getHeight();
var links = SpreadsheetApp.getActiveSheet()
.getRange("A2:A" + height)
.getValues();
var nameValues = [];
links.forEach((row) => {
try {
var link = row[0];
var fileID = getIdFromLink(link);
var name = DriveApp.getFileById(fileID).getName();
nameValues.push([name]);
} catch (e) {
nameValues.push(["NO NAME FOUND"]);
}
});
var nameRange = SpreadsheetApp.getActiveSheet().getRange("B2:B" + height);
nameRange.setValues(nameValues);
}
function getIdFromLink(link) {
var regex = new RegExp(
/(?<=https:\/\/drive\.google\.com\/file\/d\/)(.+)(?=\/)/
);
return regex.exec(link)[0];
}
Run the getNames function. The first time it will ask you to grant some permissions, grant them. Then it should fill in the files names.
References
Apps Script Overview
Spreadsheet service in Apps Script
Drive service in Apps Script

google rest api reverse image search

I am trying to do a reverse image search with the Google REST API with an image stored locally. I am using the new--not deprecated--REST API. I can do a text search and get results. I can not do a search with a local image. I can do a reverse image search on the image and get a result. Any suggestions?
My https string is:
https://www.googleapis.com/customsearch/v1?key=A******&cx=0****&q=file:///home/givonz/donald-trump-voicemail-feature.jpg
Also, tried this https string, which doesn't work either:
https://www.googleapis.com/customsearch/v1?key=A******&cx=0****&searchType=image&q=file:///home/givonz/donald-trump-voicemail-feature.jpg
This text string search works:
https://www.googleapis.com/customsearch/v1?key=A******&cx=0****&q=Some+String
It seems the service is deprecated and no longer available as an API and; it always needed a link (URL). There are a few services on the web that seem to provide the function. Bing, in spite of appearing to do so, doesn't seem to. Yahoo does a reverse image search, but, I couldn't find an API. "Incandescent" does provide this service and with an API.
This should work. Make sure you pass your key in the header.
var path = #"YOUR_IMAGE_PATH";
var url = "https://api.cognitive.microsoft.com/bing/v7.0/images/details?modules=similarimages";
using (var client = new HttpClient())
using (Stream imageFileStream = File.OpenRead(path))
{
var content = new MultipartFormDataContent();
var strContent = new StreamContent(imageFileStream);
strContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = "anynameworks" };
content.Add(strContent);
var message = await client.PostAsync(url, content);
return await message.Content.ReadAsStringAsync();
}

Can you call an external API to shorten links based on google sheets input?

I have a spreadsheet that contains links created after a form entry. I'd like to call the external API of a link shortening service (not google's link shorten-er) to take the link created in a given cell, shorten it, return the value and have Google Apps Script insert that shortened link into a new cell.
Is this possible? Specifically, can I use jQuery's AJAX methods? Where should I start.
By checking the internet, I found this stackExchange question, you can try to follow the solution in this post. What you need here is URL shortener API under the resources in the script editor (Tools > Script editor) select the Advanced Google Services and activate the UrlShortener.
Here is the sample code that you need to use.
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("Shorten")
.addItem("Go !!","rangeShort")
.addToUi()
}
function rangeShort() {
var range = SpreadsheetApp.getActiveRange(), data = range.getValues();
var output = [];
for(var i = 0, iLen = data.length; i < iLen; i++) {
var url = UrlShortener.Url.insert({longUrl: data[i][0]});
output.push([url.id]);
}
range.offset(0,1).setValues(output);
}
For more information, explanation and some sample pictures, just check the link above.

Precache / Preload directory

Been looking around for ways to preload a directory of images, found this to be the best script provided here: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
I like this best as it waits for current document to load before preloading, but I'd like to get this guy to load a directory of images instead of having to specify each file, and am pretty new to javascript, any help appreciated.
function preloader() {
if (document.images) {
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
img1.src = "http://domain.tld/path/to/image-001.gif";
img2.src = "http://domain.tld/path/to/image-002.gif";
img3.src = "http://domain.tld/path/to/image-003.gif";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);
There is no general way to accomplish this. You need some way to retrieve the contents of a directory from the server, and there is no guarantee that your web server will provide a listing. In general, most web servers do not allow a client to list the contents of a server side directory.
If you control the Web Server, you can configure it so that a directory listing is shown, for example, when you ask for "http://domain.tld/path/to/". But even then, the format of the returned response will likely be different, depending on the web server.
However, if you are able to get a listing of the images in a given directory from the server, you will still need to use some technique such as AJAX, or a hidden IFRAME, to load those image names. Then you could use JavaScript to iterate over the file names, construct the URL, and make an Image object for each.

Resources