Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @fileoverview Resizes all images in a document to a desired width
- * while limited to a max size. Sizes are in cm.
- *
- * This code is meant to be implemented as a script on a Google Docs
- * document: Tools > Script editor.
- *
- * Once open, paste the code, adjust your desired sizes and run:
- * `resizeToDesiredWidth`.
- *
- * Justification for the inconsistent and outdated syntax:
- * The current version of Apps Script does not fully support ES6.
- * As a result, this code is a mix of both. For example, `const`
- * are not allowed at global level, but they are within blocks
- * or functions. Similarly, functions declared as:
- * `function name() {}` are detected to be run by the script, but
- * `const name = function() {}` would not. Arrow functions or
- * nice loop logic are not implemented.
- */
- /** Configure the desired width and max height of the images. */
- var DESIRED_WIDTH_CM = 15;
- var MAX_HEIGHT_CM = 8;
- /** This PPI is based on my experience. It may differ for you. */
- var PIXELS_PER_CM = 39;
- /**
- * Resizes all images in the document based on desired and max size.
- */
- function resizeToDesiredWidth() {
- const document = DocumentApp.getActiveDocument();
- const body = document.getBody();
- const images = body.getImages();
- images.forEach(function(image) {
- const w = pxToCm(image.getWidth());
- const h = pxToCm(image.getHeight());
- const newDimensions = getDesiredImageSize(w, h);
- const newW = newDimensions[0];
- const newH = newDimensions[1];
- image.setWidth(cmToPx(newW));
- image.setHeight(cmToPx(newH));
- });
- }
- /**
- * Calculates new sizes of images adjusted to desired and max.
- * Image ratio is preserved.
- * Resize calculation is done to DESIRED_WIDTH_CM.
- * If image is over MAX_HEIGHT_CM, then image is resized to MAX_HEIGHT_CM.
- * @param {number} imageW Image width in cm.
- * @param {number} imageH Image height in cm.
- * @return {!Array<number>} New image dimensions: [newImageW, newImageH]
- */
- var getDesiredImageSize = function(imageW, imageH) {
- const ratioW = imageW / DESIRED_WIDTH_CM;
- var newW = DESIRED_WIDTH_CM;
- var newH = imageH / ratioW;
- if (newH <= MAX_HEIGHT_CM) {
- return [newW, newH];
- }
- const ratioH = newH / MAX_HEIGHT_CM;
- newW = newW / ratioH;
- newH = MAX_HEIGHT_CM;
- return [newW, newH];
- };
- /**
- * Converts a measure in pixels to cm.
- * @param {number} measureInPx
- * @return {number} Equivalent measure in cm.
- */
- var pxToCm = function(measureInPx) {
- return measureInPx / PIXELS_PER_CM;
- };
- /**
- * Converts a measure in cm to pixels.
- * @param {number} measureInCm
- * @return {number} Equivalent measure in pixels.
- */
- var cmToPx = function(measureInCm) {
- return measureInCm * PIXELS_PER_CM;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement