Skip to content

Instantly share code, notes, and snippets.

Last active May 26, 2020
What would you like to do?
Update Images by URL
* Updates images by there URL. Run when image changes
* This only works for images that have a link to themselves in a google doc
* To link an image right mouse click and select link. Put a link to the image URL there
* URLs for images in Drive take the form ID HERE##
* Will replace image with same dimensions. Will not match rotation angle.
* I think the URLs need to be http rather than https to work consistently.
function replace_images_url() {
// Open the document by id
var body = DocumentApp.openById(### DOC ID GOES HERE ###).getBody();
// Locate the old image for updating
//This is the section that needs work. Need to identify images in doc by their drive id
var olds = body.getImages();
// loop through image list
for (const [i,v] of olds.entries()){
// the old image
var old = olds[i];
var old_link = old.getLinkUrl()
//get the new image
var response = UrlFetchApp.fetch(old_link);
var binaryData = response.getContent();
//get blob
var blob = Utilities.newBlob(binaryData, 'image/png','myImage');
//get the location of the old image
var parent = old.getParent();
//insert new image in front of it
var img = parent.insertInlineImage(parent.getChildIndex(old)+1, blob);
//set width and higher of new image to that of the old image
var w = old.getWidth();
var h = old.getHeight();
img.setHeight(w * h / w);
//delete the old image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment