Extract width and height from image links via ImgApp Google Sheet Library - image

I want to extract the dimensions of the image from the URL in google Sheet. Found this Library that does exactly what I am after.
https://github.com/tanaikech/ImgApp#getsize
But I am very new to this scenario and wondering what exactly I should use in the script editor. If I follow the above I can't get the results.
Please help.
Thanks

When I saw your provided sample Spreadsheet, it seems that the Spreadsheet and your script are as follows.
function myFunction() {
var blob = DriveApp.getFileById(fileId).getBlob();
var res = ImgApp.getSize(blob);
var width = res.width;
var height = res.height;
}
Modification points:
In this case, you put a custom function of =myFunction(A2) to a cell. But your script doesn't retrieve the value.
At the custom function, DriveApp.getFileById(fileId) cannot be used because of the limitation.
Your script doesn't return the values.
When these points are reflected in the script for achieving your goal, it becomes as follows.
Modified script:
Please replace your current script with the following script and save the script. And, please put a custom function of =myFunction(A2) to a cell. By this, the width and height are returned.
function myFunction(url) {
const blob = UrlFetchApp.fetch(url).getBlob();
const { width, height } = ImgApp.getSize(blob);
return [[width, height]];
}
Testing:
When this modified script is used for your sample Spreadsheet, it becomes as follows.
References:
Custom Functions in Google Sheets
ImgApp

Related

Auto Import Image in sheet?

I run my own fantasy baseball yearly projections and I'm looking to automatically add player images to a sheet I created.
Test Page
I use a formula to create a link to the player's image page on ESPN.
https://a.espncdn.com/combiner/i?img=/i/headshots/mlb/players/full/33859.png
Is there a way to automatically add the player image to the page?
=image("Link") is the formula, but i cant use the cell location as the link.
Any advise or guidance will be helpful and appreciated
I created an Apps Script method to achieve your target as it is not possible to do it using formula.
Here's the script I did with comments:
function SpecialOnEdit(e) {
//Get the edited cell
var range = e.range;
//Get the active sheet
var sheet = SpreadsheetApp.getActiveSheet();
//Download the image. (e.value is the URL in Google sheet)
var response = UrlFetchApp.fetch(e.value);
//Get the binary data of the image and create a blob object
var binaryData = response.getContent();
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
//Insert the image into the same row that the user place the image URL link
var image = sheet.insertImage(blob, range.getHeight(), range.getRow());
//Set the height of the row, show that the image can fit the row
sheet.setRowHeight(range.getRow(), image.getHeight() + 10);
}
You should add triggers next after pasting the script. Go to your Script Editor and click Edit->Current project's triggers->Add Trigger->under Select event type, select On edit->click Save
Next, to test the trigger and script, paste a URL of a PNG image format in the spreadsheet to validate the result.
Here's a sample output of the script and trigger:

Sorting google-sheet values by cells color directly in Apps Script

Early this year (i think) Google released the functionality to sort (and filter) by colors in google-sheet.
I wanna use this feature in my sheets, but all my sorts are done programmatically within my scripts using (for a simplified example) :
SpreadsheetApp.getActive().getSheetByName("Test").getRange("A:I").sort({column 2, ascending: false}); (as in reality the parameters will be calculated outside the sort, but that's not the issue here).
I'm struggling to find documentation or examples to fill the SortSpecObj passed to the Range.sort() function to add conditions on cell color. I've tried: color, background, bgcolor, fill, fillcolor, ... but none of them seems to work.
I'm not trying to extract the values from the sheet to sort them and push them back into the sheet, and I'm also not looking to add another column to my sheet with and numerical value to do the sorting. I want to access with code to the functionality available graphically in the web application.
Or if we can override the sort function used by the class Range, but as the code is native, I don't think it will be possible, or the performances will be way too much impacted.
Thanks a lot in advance.
I believe your goal as follows.
You want to sort the range by the background color of the cells using Google Apps Script.
Issue and workaround:
Unfortunately, in the current stage, it seems that sort(sortSpecObj) of Class Range cannot sort by the background colors of cells. But when Sheets API is used, I thought that your goal can be achieved. In this answer, as a workaround, I would like to propose to use "SortRangeRequest" of the method of "spreadsheets.batchUpdate" in Sheets API.
The flow of this sample script is as follows.
Retrieve the background colors from the cells.
Create the request body for using the batchUpdate method of Sheets API.
Request to Sheets API using the request body.
Sample script:
The sample script is as follows. Please copy and paste the following script to the script editor of the container-bound script of Spreadsheet. And please enable Sheets API at Advanced Google services. By this, Sheets API can be used with Google Apps Script.
function myFunction() {
const sheetName = "Sheet1"; // Please set the sheet name.
const a1Notation = "A1:C10"; // Please set the sort range as a1Notation.
// 1. Retrieve the background colors from the cells.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName);
const range = sheet.getRange(a1Notation);
const backgrounds = range.getBackgroundObjects();
// 2. Create the request body for using the batchUpdate method of Sheets API.
const backgroundColors = Object.values(
backgrounds.reduce((o, [a]) => {
const rgb = a.asRgbColor();
return Object.assign(o, {[rgb.asHexString()]: {red: rgb.getRed() / 255, green: rgb.getGreen() / 255, blue: rgb.getBlue() / 255}})
}, {})
);
const startRow = range.getRow() - 1;
const startColumn = range.getColumn() - 1;
const srange = {
sheetId: sheet.getSheetId(),
startRowIndex: startRow,
endRowIndex: startRow + range.getNumRows(),
startColumnIndex: startColumn,
endColumnIndex: startColumn + range.getNumColumns()
};
const requests = [
{sortRange: {range: srange, sortSpecs: [{dimensionIndex: 0, sortOrder: "ASCENDING"}]}},
{sortRange: {range: srange, sortSpecs: backgroundColors.map(rgb => ({backgroundColor: rgb}))}}
];
// 3. Request to Sheets API using the request body.
Sheets.Spreadsheets.batchUpdate({requests: requests}, ss.getId());
}
In this sample, before the sort of background color is run, the column "A" is sorted with "ASCENDING".
Result:
When above script is used, the following result can be obtained.
Note:
If you want to set the order of colors, please set the array for sortSpecs like sortSpecs: [{backgroundColor: rgb1}, {backgroundColor: rgb2}, {backgroundColor: rgb3},,,].
References:
sort(sortSpecObj)
Method: spreadsheets.batchUpdate
SortRangeRequest

A script to update linked sheet from google doc

I have linked part of a sheet in google doc (as linked object). Now, whenever I change the sheet data, I can click a button in google doc and the data is reflected in the google doc linked sheet too (this is all built in google doc stuff).
What I want to do is the other side of this. I am able to see a bunch of data in one place (google doc) based on the sheets I have linked. I would like to update the data in the google doc, and "upload" it to the linked google sheets.
I am trying to write a script to do that. But cannot seem to find any method to access linked sheets. I found this slides API page that can does the sheet -> slide syncing.
I am looking at the document API page, but I scanning through add... and get... methods, I don't see to find any way to get linked objects. Is it represented as NamedRange? If so, how do I access it?
There was another similar question, but without any satisfactory answer.
If you can share some pointers to get started, I would appreciate it.
Edit: Here is an example doc (and a spreadsheet contained their in) to explain the situation clearer.
Test document for updating spreadsheet - Google Docs
You can find the Table elements in your Document via findElement(elementType). If that's the only Table in your Document, as in the sample you shared, this is immediate.
Once you retrieve the Table, you can loop through its rows and cells and come up with a 2D array with the values from the table:
function getTableValues() {
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();
const table = body.findElement(DocumentApp.ElementType.TABLE).getElement();
let tableValues = [[]];
for (let i = 0; i < table.getNumRows(); i++) {
const tableRow = table.getRow(i);
for (let j = 0; j < tableRow.getNumCells(); j++) {
const tableCell = tableRow.getCell(j);
const text = tableCell.getText();
tableValues[i].push(text);
}
if (i == table.getNumRows() - 1) break;
tableValues.push([]);
}
return tableValues;
}
Once you've done that, you just need to copy it to your spreadsheet via setValues(values):
function copyToSheet(tableValues, spreadsheetId) {
const sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName("Sheet1");
sheet.getRange(1, 1, tableValues.length, tableValues[0].length).setValues(tableValues);
}
Calling both of these in the same function, you would get this:
function main() {
const tableValues = getTableValues();
const spreadsheetId = "{your-spreadsheet-id}";
copyToSheet(tableValues, spreadsheetId);
}
Note:
getActiveDocument() is used to retrieve the Document, so this assumes the script is bound to your Document. If that's not the case, use openById(id) or openByUrl(url) instead.

Google Script - Import images and list file names

Maybe this is one of the impossible ones, but here goes.
I have a ton of images of qr-codes in a folder. It doesnt matter if its in google drive or in a local folder for me.
I would a script that automaticly loads all images in column A and then the file names in column B. AND automaticly adds new images when uploaded to the google drive folder.
Example:
Qr1.jpeg will be loaded into cell a1 and cell b1 will be "Qr1"
Qr2.jpeg will be loaded into cell a2 and so on..
It would be nice if the images are scaled to 10x10 cm. :)
Is this even possible?
Hope you guys can help!
Thanks!
Oliver
Not the Complete Answer...but it's a part
I've been working on getting thumbnails into my spreadsheet ever since you asked this question. I won't go into all the paths I took but I finally found this Github link in the comments of this issue
Which resulted in the following code:
function myImageFiles()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('MyImages');
var files = DriveApp.getFiles();
var s='';
var cnt=1;
while(files.hasNext())
{
var fi=files.next();
var type=fi.getMimeType();
if(type==MimeType.GIF || type==MimeType.JPEG || type==MimeType.PNG)
{
sh.appendRow([cnt++,fi.getName(),type,fi.getUrl(),'=IMAGE("' + getThumbNailLink(fi.getId()) + '",1)']);
}
}
}
function getThumbNailLink(fileId)
{
var file=Drive.Files.get(fileId);
return file.thumbnailLink;
}
The result is now I have a spreadsheet with all of my image filenames and thumbnails. You'll need Advanced Drive and take a close look at getThumbNailLink().

Find&Replace script in Google Docs SpreadSheets

I have google spreadsheet with direct links to images (jpg and png):
https://docs.google.com/spreadsheet/ccc?key=0AoPGWppcjtzhdDh6MW1QNVJhSHlwVTlfRnRtd0pvNGc&usp=sharing
I want to increase rows heights starting from "2nd row" to 100px and render images there.
It's possible to do via Find&Replace:
Find jpg and Replace to jpg", 1)
Find http://img and Replace to =image("http://img)
Select rows and Scale them
and the same for png image-urls.
Watch this screencast http://www.screenr.com/S0RH
Is it possible to automate it via script? I think - YES! It have to be pretty simple but I googled a lot but haven't found the solution. I can't do it myself as don't know coding. Will anyone help and make this script?
A function to do what you ask is simple, if you have a basic understanding of the language (Javascript), know how to use the development environment, and read the API documentation.
For example, see this script. It's been added to your shared spreadsheet, so you can also view it (and run it) in the script editor there.
/**
* Scan column A, looking for images that have been inserted using
* =image() function. For any row with an image, set the row height
* to 100 pixels.
*/
function resizeImageRows() {
var sheet = SpreadsheetApp.getActiveSheet(); // Get a handle on the sheet
var HEADERS = 1; // Number of header rows at top
var firstRow = HEADERS + 1; // First row with data
var lastRow = sheet.getLastRow(); // Last row with data
var imageRange = sheet.getRange(1, 1, lastRow, 1); // Column A
// Get all formulas from Column A, without Headers
var formulas = imageRange.getFormulas().slice(HEADERS);
// Look for image() formulas, and set the row height.
for (var i = 0; i< formulas.length; i++) {
if (formulas[i][0].indexOf('image') !== -1) {
sheet.setRowHeight(i+firstRow, 100); // Set height to 100 pixels
}
}
}
You can absolutely do this with the find and replace function under the edit menu, just make sure you click "search in formulas" and it will find and replace in the formula.

Resources