Last active
November 10, 2023 03:02
-
-
Save canpolat/7a8f4597494ace8aeebe775a1a734450 to your computer and use it in GitHub Desktop.
Google Apps Script: Upload image to TinyPNG
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var TINYPNG_API_KEY = "YOUR-TINYPNG-API-KEY"; | |
var UPLOAD_TEST_FILE_ID = "GOOGLE-DRIVE-IMAGE-TEST-FILE-ID"; | |
var TINYPNG_API_BASE_URL = "https://api.tinify.com"; | |
var TINYPNG_API_UPLOAD_URL = TINYPNG_API_BASE_URL + "/shrink"; | |
function uploadImageToTinyPng(blob) { | |
Logger.log("Uploading image to TingPNG"); | |
var uploadParams = { | |
"method": "POST", | |
"muteHttpExceptions": true, | |
"payload": blob.getBytes(), | |
"contentLength": blob.getBytes().length, | |
"headers": { | |
"Authorization": "Basic " + Utilities.base64EncodeWebSafe("api:" + TINYPNG_API_KEY) | |
} | |
}; | |
// UrlFetchApp may throw | |
var response = UrlFetchApp.fetch(TINYPNG_API_UPLOAD_URL, uploadParams); | |
if(response.getResponseCode() > 299) | |
{ | |
throw "TinyPNG Error: Upload operation failed with response code: " + response.getResponseCode(); | |
} | |
return response.getHeaders().Location; | |
} | |
//------------------------------------- | |
function testTinyPngUpload() { | |
var pdfFile = DriveApp.getFileById(UPLOAD_TEST_FILE_ID); | |
try { | |
var imageUrl = uploadImageToTinyPng(pdfFile.getThumbnail()); | |
Logger.log(imageUrl); | |
} | |
catch (err) { | |
Logger.log("Problem uploading the image: " + err); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment