Skip to content

Instantly share code, notes, and snippets.

@pdparker
Last active May 26, 2020 23:48
Show Gist options
  • Save pdparker/fecf1be5516bff4582a400e04ffba2cb to your computer and use it in GitHub Desktop.
Save pdparker/fecf1be5516bff4582a400e04ffba2cb to your computer and use it in GitHub Desktop.
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 http://drive.google.com/uc?export=view&id=##IMAGE 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.setWidth(w);
img.setHeight(w * h / w);
img.setLinkUrl(old_link);
//delete the old image
old.removeFromParent();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment