How to make an image smaller while leaving the it in it's original proportions? - google-apps-script

I'm trying to add a list of images from my Google drive to a Google doc using Google apps script.
I made a list named images_list of links to the images that are in my Drive.
I was able to add all the content I need to the doc and the images at the end of it.
Currently the images are huge in their size, and I turned it into 400X400.
The problem is that not all them are square.
How can I make the image smaller while leaving the image in it's original proportions?
This is the code I'm using:
if(images_list[0]){
for(var i=0; i<images_list.length; i++){
try{
var imageID = images_list[i].slice(32,65);
var blob = DriveApp.getFileById(imageID).getBlob();
var imgDoc = body.appendImage(blob);
imgDoc.setWidth(400).setHeight(400)
bullet_index = bullet_index+1
}catch(e){}
}
}
Thanks!

For example it could be something like this:
if (images_list[0]) {
for (var i = 0; i < images_list.length; i++) {
try {
var imageID = images_list[i].slice(32, 65);
var blob = DriveApp.getFileById(imageID).getBlob();
var max = 400;
var w = imgDoc.getWidth();
var h = imgDoc.getHeight();
if (w > h) { h = h * (max / w); w = max }
else { w = w * (max / h); h = max }
imgDoc.setWidth(w).setHeight(h);
bullet_index = bullet_index + 1
} catch (e) { }
}
}
It will fit any image into a square 400x400 px while keeping the aspect ratio.

Related

Maximum size of cards inside a canvas

I am now working with a Web Application, which needs to draw some cards on a fixed rectangle canvas. Below is the criteria:
The canvas size is fixed with width "w" and height "h" when the Web Application starts.
There are "n" no. of cards which won't be changed after started.
All cards must in the same size, which has a fixed ratio with width "cw" and height "ch", the cards are able to re-size within the canvas.
I would like to calculate the maximum width and height of each card in such cases. Can anybody help?
Your question is lacking a lot of information. please read the comments in the code. I hope my answer may help you.
// initiate the canvas
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 300,
cx = cw / 2;
let ch = canvas.height = 300,
cy = ch / 2;
// number of cards
let n = 12;
// the horizontal and vertical ratio
let ratio = {x:.2,y:.3}
// the width and the height of a card
let w = cw*ratio.x;
let h = ch*ratio.y;
// a counter
let i = 0;
//a double for loop to draw the cards
for(let y = 0; y<ch; y+=h){
for(let x = 0; x<cw; x+=w){
if(i < n)
{drawCard(x,y);
i++}
}
}
function drawCard(x,y){
ctx.beginPath();
ctx.strokeRect(x,y,w,h);
}
canvas {
border:1px solid #d9d9d9;
}
<canvas id="canvas"></canvas>
Finally, I found the solution myself.
This performance may not is the optimal one, but the solution gives me the new card width, new card height, cards per rows and cards per column. So that the cards can almost cover the canvas.
function crwh(col, row, n, cw, ch, w, h, exactN) {
// Methods
this.fn_init = function(col, row) {
this.col = col;
this.row = row;
if (this.col > 0 && this.row > 0) {
// Calculate new card width & card height base on col
this.cw_new = (this.w / this.col);
this.ch_new = (this.cw_new / this.cw * this.ch);
if (this.fn_valid() == false) {
// Calculate new card height & card width base on row
this.ch_new = (this.h / this.row);
this.cw_new = (this.ch_new / this.ch * cw);
}
}
}
this.fn_area = function() {
// Get the size the rectangle
return this.cw_new * this.ch_new;
}
this.fn_valid = function() {
var valid = true;
// True if col * row must equal to no. of cards, False allow col * row greater than no. of cards
valid = valid && ((this.exactN == true && (this.col * this.row) == this.n) || (this.exactN == false && (this.col * this.row) >= this.n));
// col * card width (new) must be shorter than canvas width
valid = valid && ((this.col * this.cw_new) <= this.w);
// row * card height (new) must be shorter than canvas height
valid = valid && ((this.row * this.ch_new) <= this.h);
return valid;
}
// Properties
this.n = n;
this.cw = cw;
this.ch = ch;
this.w = w;
this.h = h;
this.exactN = exactN;
this.col = 0;
this.row = 0;
this.cw_new = 0;
this.ch_new = 0;
this.fn_init(col, row);
}
function fn_getCardDimensions(n, cw, ch, w, h, exactN) {
var crwh_max = new crwh(0, 0);
// Loop thru 1 to n for col & row to see which combination allow a maximum card size
for (var col = 1; col <= n; col++) {
for (var row = 1; row <= n; row++) {
if ((col * row) >= n) {
var crwh_cur = new crwh(col, row, n, cw, ch, w, h, exactN);
if (crwh_cur.fn_valid()) {
if (crwh_cur.fn_area() > crwh_max.fn_area()) {
crwh_max = crwh_cur;
}
}
}
}
}
return [crwh_max.col, crwh_max.row, crwh_max.cw_new, crwh_max.ch_new];
}
var n = 80; // No. of Cards
var cw = 344; // Card Width (orig)
var ch = 512; // Card Height (orig)
var w = 0; // Canvas Width
var h = 0; // Canvas Height
var exactN = true; // True if col * row must equal to no. of cards
function fn_drawCards() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
[col, row, cw_new, ch_new] = fn_getCardDimensions(n, cw, ch, w, h, exactN);
for (var i = 0; i < col; i++) {
for (var j = 0; j < row; j++) {
ctx.beginPath();
ctx.strokeRect(i * cw_new, j * ch_new, cw_new, ch_new);
}
}
}
fn_drawCards();
canvas {
border:1px solid #00FF00;
}
<canvas id="canvas"></canvas>

Check if image A exists in image B

I need to check if an image exists in another image using JavaScript, I need to know what are the best approaches (algorithm) and solutions (ex: librarie) to do this operations
I explained what I need to do in this image:
Using the GPU to help in image processing.
Using the 2D API and some simple tricks you can exploit the GPUs power to speed up Javascript.
Difference
To find an image you need to compare the pixels you are looking for (A) against the pixels in the image (B). If the difference between the Math.abs(A-B) === 0 then the pixels are the same.
A function to do this may look like the following
function findDif(imageDataSource, imageDataDest, xx,yy)
const ds = imageDataSource.data;
const dd = imageDataDest.data;
const w = imageDataSource.width;
const h = imageDataSource.height;
var x,y;
var dif = 0;
for(y = 0; y < h; y += 1){
for(x = 0; x < w; x += 1){
var indexS = (x + y * w) * 4;
var indexD = (x + xx + (y + yy) * imageDataDest.width) * 4;
dif += Math.abs(ds[indexS]-dd[indexD]);
dif += Math.abs(ds[indexS + 1]-dd[indexD + 1]);
dif += Math.abs(ds[indexS + 2]-dd[indexD + 2]);
}
}
return dif;
}
var source = sourceCanvas.getContext("2d").getImageData(0,0,sourceCanvas.width,sourceCanvas.height);
var dest = destinationCanvas.getContext("2d").getImageData(0,0,destinationCanvas.width,destinationCanvas.height);
if(findDif(source,dest,100,100)){ // is the image at 100,100?
// Yes image is very similar
}
Where the source is the image we are looking for and the dest is the image we want to find it in. We run the function for every location that the image may be and if the result is under a level then its a good chance we have found it.
But this is very very slow in JS. This is where the GPU can help.
Using the ctx.globalCompositeOperation = "difference"; operation we can speed up the process as it will do the difference calculation for us
When you render with the comp operation "difference" the resulting pixels are the difference between the pixels you are drawing and those that are already on the canvas. Thus if you draw on something that is the same the result is all pixels are black (no difference)
To find a similar image in the image you render the image you are testing for at each location on the canvas that you want to test for. Then you get the sum of all the pixels you just rendered on, if the result is under a threshold that you have set then the image under that area is very similar to the image you are testing for.
But we still need to count all the pixels one by one.
A GPU mean function
The comp op "difference" already does the pixel difference calculation for you, but to get the sum you can use the inbuilt image smoothing.
After you have rendered to find the difference you take that area and render it at a smaller scale with ctx.imageSmoothingEnabled = true the default setting. The GPU will do something similar to an average and can reduce the amount of work JS has to do by several orders of magnitude.
Now instead of 100s or 1000s of pixels you can reduce it down to as little at 4 or 16 depending on the accuracy you need.
An example.
Using these methods you can get a near realtime image in image search with just the basic numerical analysis.
Click to start a test. Results are shown plus the time it took. The image that is being searched for is in the top right.
//------------------------------------------------------------------------
// Some helper functions
var imageTools = (function () {
var tools = {
canvas(width, height) { // create a blank image (canvas)
var c = document.createElement("canvas");
c.width = width;
c.height = height;
return c;
},
createImage : function (width, height) {
var i = this.canvas(width, height);
i.ctx = i.getContext("2d");
return i;
},
image2Canvas(img) {
var i = this.canvas(img.width, img.height);
i.ctx = i.getContext("2d");
i.ctx.drawImage(img, 0, 0);
return i;
},
copyImage(img){ // just a named stub
return this.image2Canvas(img);
},
};
return tools;
})();
const U = undefined;
const doFor = (count, callback) => {var i = 0; while (i < count && callback(i ++) !== true ); };
const setOf = (count, callback) => {var a = [],i = 0; while (i < count) { a.push(callback(i ++)) } return a };
const randI = (min, max = min + (min = 0)) => (Math.random() * (max - min) + min) | 0;
const rand = (min, max = min + (min = 0)) => Math.random() * (max - min) + min;
const randA = (array) => array[(Math.random() * array.length) | 0];
const randG = (min, max = min + (min = 0)) => Math.random() * Math.random() * Math.random() * Math.random() * (max - min) + min;
// end of helper functions
//------------------------------------------------------------------------
function doit(){
document.body.innerHTML = ""; // clear the page;
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
// a grid of 36 images
canvas.width = 6 * 64;
canvas.height = 6 * 64;
console.log("test");
// get a random character to look for
const digit = String.fromCharCode("A".charCodeAt(0) + randI(26));
// get some characters we dont want
const randomDigits = setOf(6,i=>{
return String.fromCharCode("A".charCodeAt(0) + randI(26));
})
randomDigits.push(digit); // add the image we are looking for
var w = canvas.width;
var h = canvas.height;
// create a canvas for the image we are looking for
const imageToFind = imageTools.createImage(64,64);
// and a larger one to cover pixels on the sides
const imageToFindExtend = imageTools.createImage(128,128);
// Draw the character onto the image with a white background and scaled to fit
imageToFindExtend.ctx.fillStyle = imageToFind.ctx.fillStyle = "White";
imageToFind.ctx.fillRect(0,0,64,64);
imageToFindExtend.ctx.fillRect(0,0,128,128);
ctx.font = imageToFind.ctx.font = "64px arial black";
ctx.textAlign = imageToFind.ctx.textAlign = "center";
ctx.textBaseline = imageToFind.ctx.textBaseline = "middle";
const digWidth = imageToFind.ctx.measureText(digit).width+8;
const scale = Math.min(1,64/digWidth);
imageToFind.ctx.fillStyle = "black";
imageToFind.ctx.setTransform(scale,0,0,scale,32,32);
imageToFind.ctx.fillText(digit,0,0);
imageToFind.ctx.setTransform(1,0,0,1,0,0);
imageToFindExtend.ctx.drawImage(imageToFind,32,32);
imageToFind.extendedImage = imageToFindExtend;
// Now fill the canvas with images of other characters
ctx.fillStyle = "white";
ctx.setTransform(1,0,0,1,0,0);
ctx.fillRect(0,0,w,h);
ctx.fillStyle = "black";
ctx.strokeStyle = "white";
ctx.lineJoin = "round";
ctx.lineWidth = 12;
// some characters will be rotated 90,180,-90 deg
const dirs = [
[1,0,0,1,0,0],
[0,1,-1,0,1,0],
[-1,0,0,-1,1,1],
[0,-1,1,0,0,1],
]
// draw random characters at random directions
doFor(h / 64, y => {
doFor(w / 64, x => {
const dir = randA(dirs)
ctx.setTransform(dir[0] * scale,dir[1] * scale,dir[2] * scale,dir[3] * scale,x * 64 + 32, y * 64 + 32);
const d = randA(randomDigits);
ctx.strokeText(d,0,0);
ctx.fillText(d,0,0);
});
});
ctx.setTransform(1,0,0,1,0,0);
// get a copy of the canvas
const saveCan = imageTools.copyImage(ctx.canvas);
// function that finds the images
// image is the image to find
// dir is the matrix direction to find
// smapleSize is the mean sampling size samller numbers are quicker
function checkFor(image,dir,sampleSize){
const can = imageTools.copyImage(saveCan);
const c = can.ctx;
const stepx = 64;
const stepy = 64;
// the image that will contain the reduced means of the differences
const results = imageTools.createImage(Math.ceil(w / stepx) * sampleSize,Math.ceil(h / stepy) * sampleSize);
const e = image.extendedImage;
// for each potencial image location
// set a clip area and draw the source image on it with
// comp mode "difference";
for(var y = 0 ; y < h; y += stepy ){
for(var x = 0 ; x < w; x += stepx ){
c.save();
c.beginPath();
c.rect(x,y,stepx,stepy);
c.clip();
c.globalCompositeOperation = "difference";
c.setTransform(dir[0],dir[1],dir[2],dir[3],x +32 ,y +32 );
c.drawImage(e,-64,-64);
c.restore();
}
}
// Apply the mean (reducing nnumber of pixels to check
results.ctx.drawImage(can,0,0,results.width,results.height);
// get the pixel data
var dat = new Uint32Array(results.ctx.getImageData(0,0,results.width,results.height).data.buffer);
// for each area get the sum of the difference
for(var y = 0; y < results.height; y += sampleSize){
for(var x = 0; x < results.width; x += sampleSize){
var val = 0;
for(var yy = 0; yy < sampleSize && y+yy < results.height; yy += 1){
var i = x + (y+yy)*results.width;
for(var xx = 0; xx < sampleSize && x + xx < results.width ; xx += 1){
val += dat[i++] & 0xFF;
}
}
// if the sum is under the threshold we have found an image
// and we mark it
if(val < sampleSize * sampleSize * 5){
ctx.strokeStyle = "red";
ctx.fillStyle = "rgba(255,0,0,0.5)";
ctx.lineWidth = 2;
ctx.strokeRect(x * (64/sampleSize),y * (64/sampleSize),64,64);
ctx.fillRect(x * (64/sampleSize),y * (64/sampleSize),64,64);
foundCount += 1;
}
}
}
}
var foundCount = 0;
// find the images at different orientations
var now = performance.now();
checkFor(imageToFind,dirs[0],4);
checkFor(imageToFind,dirs[1],6); // rotated images need larger sample size
checkFor(imageToFind,dirs[2],6);
checkFor(imageToFind,dirs[3],6);
var time = performance.now() - now;
var result = document.createElement("div");
result.textContent = "Found "+foundCount +" matching images in "+time.toFixed(3)+"ms. Click to try again.";
document.body.appendChild(result);
// show the image we are looking for
imageToFind.style.left = (64*6 + 16) + "px";
imageToFind.id = "lookingFor";
document.body.appendChild(imageToFind);
}
document.addEventListener("click",doit);
canvas {
border : 2px solid black;
position : absolute;
top : 28px;
left : 2px;
}
#lookingFor {
border : 4px solid red;
}
div {
border : 2px solid black;
position : absolute;
top : 2px;
left : 2px;
}
Click to start test.
Not perfect
The example is not perfect and will sometimes make mistakes. There is a huge amount of room for improving both the accuracy and the speed. This is just something I threw together as an example to show how to use the GPU via the 2D API. Some further maths will be needed to find the statistically good results.
This method can also work for different scales, and rotations, you can even use some of the other comp modes to remove colour and normalize contrast. I have used a very similar approch to stabilize webcam by tracking points from one frame to the next, and a veriaty of other image tracking uses.

My bar charts overlap eachother. Need help to solve it

im making a code where I have an input field and a button on my screen. In the code below btnLeggTil (its norwegian) adds the number you wrote in the input field. It determines the height of the bars. My code is supposed to let the user add bars of whatever the height he/she prefers. As you can see I have put alot of my code inside a loop. The problem with the code is that the bars it makes, overlap eachother. I need to have a space between each bar, but don't know how. Thanks in advance! You can test out the code yourself and see (just remember to make a button and input field with names btnLeggTil and txtInn.
("høyde" means height) ("bredde" means width) ("verdier" means values) sorry its all norwegian
var verdier:Array = new Array();
btnLeggTil.addEventListener(MouseEvent.CLICK, leggtil);
function leggtil (evt:MouseEvent)
{
verdier.push(txtInn.text);
var totHøyde:int = 200; //total height on diagram
var totBredde:int = 450; //total width on diagram
var antall:int = verdier.length;
var xv:int = 50;
var yb:int = 350;
var bredde:int = (totBredde/antall) * 0.8;
var mellom:int = (totBredde/antall) * 0.2;
var maksHøyde:int = maksVerdi(verdier);
function maksVerdi(arr:Array):Number //finds the biggest value in the array
{
//copies to not destroy the order in the original
var arrKopi:Array = arr.slice();
arrKopi.sort(Array.NUMERIC|Array.DESCENDING);
return arrKopi[0];
}
for(var i:int = 0; i < verdier.length; i++)
{
graphics.lineStyle(2, 0x000000);
graphics.beginFill(0x00ff00);
graphics.drawRect(xv + (bredde+mellom)*i, yb, bredde, -verdier[i] * (totHøyde/maksHøyde));
graphics.endFill();
var txtTall = new TextField();
txtTall.x = xv + (bredde+mellom)*i + 5;
txtTall.y = yb - verdier[i] - 10;
txtTall.type = "dynamic";
txtTall.text = verdier[i];
addChild(txtTall);
}
}
You need to modify your for loop a bit,
graphics.clear();
graphics.lineStyle(2, 0x000000);
graphics.beginFill(0x00ff00);
for(var i:int = 0; i < verdier.length; i++)
{
graphics.drawRect(xv + (bredde+mellom)*i, yb, bredde, -verdier[i] * (totHøyde/maksHøyde));
var txtTall = new TextField();
txtTall.x = xv + (bredde+mellom)*i + 5;
txtTall.y = yb - verdier[i] - 10;
txtTall.type = "dynamic";
txtTall.text = verdier[i];
addChild(txtTall);
}
graphics.endFill();

Manipulate height of cells on google document using google apps script

I'm trying to draw a table on Google Document using Google Apps Script then convert the result to PDF. That works fine but I couldn't manipulate a height of cells.
Here is my code :
var TemplateCopyBody = DocumentApp.openById("id").getActiveSection();
var tableStyle = {};
tableStyle[DocumentApp.Attribute.FONT_SIZE] = 8;
tableStyle[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.UBUNTU;
tableStyle[DocumentApp.Attribute.BOLD] = 0;
tableStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = 0;
tableStyle[DocumentApp.Attribute.PADDING_RIGHT] = 0;
tableStyle[DocumentApp.Attribute.HEIGHT] = 0;
/* Function to populate my table */
var myTable = new Array();
for(var i=0;i<RESULT.marksDetails.length -1;i++){
myTable[i] = RESULT.notesDetails[i];
Logger.log("insertion table : "+i);
}
TemplateCopyBody.appendTable(myTable).setAttributes(tableStyle).setColumnWidth(0, 300);
I really need your help!
To change the height of every other row to 45 pixels, and the others to 22 pixels, I would have done something like this:
var newTable = TemplateCopyBody.appendTable(myTable);
for(var i=1; i < myTable.length ;i++){
if(i % 2 == 0)
newTable.getRow(i).setMinimumHeight(22);
else
newTable.getRow(i).setMinimumHeight(45);
}
newTable.setAttributes(tableStyle).setColumnWidth(0, 300);

trying to get the cente lat/lon of a polygon

I am trying to populate a var "polyCenter" with the latlon for the center of a polygon and its driving me insane..
var paths = MapToolbar.features["shapeTab"]["shape_1"].getPath();
var i;
for (i = 0; i < paths.length; i++) {
bounds.extend(paths[i]);
}
polyCenter = bounds.getCenter();
alert(polyCenter);
It keeps returning (0,-180) for some reason..
Mathematically an irregular polygon does not have a center. They do however have a centroid (center of gravity) that is usually the approximate center.
Here is the equation to calculate the centroid of a polygon:
The equation in JavaScript:
function GetCentroid(paths){
var f;
var x = 0;
var y = 0;
var nPts = paths.length;
var j = nPts-1;
var area = 0;
for (var i = 0; i < nPts; j=i++) {
var pt1 = paths[i];
var pt2 = paths[j];
f = pt1.lat() * pt2.lng() - pt2.lat() * pt1.lng();
x += (pt1.lat() + pt2.lat()) * f;
y += (pt1.lng() + pt2.lng()) * f;
area += pt1.lat() * pt2.lng();
area -= pt1.lng() * pt2.lat();
}
area /= 2;
f = area * 6;
return new google.maps.LatLng(x/f, y/f);
}
Here is an updated fiddle based on #Argiropoulos answer.
Take a look at an example although this is not the center of a polygon except if it's a rectangle