Last active
March 18, 2022 11:53
-
-
Save wolfposd/abdb11e008f18fe0f1510c9b0c72eeee to your computer and use it in GitHub Desktop.
PanoramaImageSplit.js for scriptable.app
This file contains 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
// Variables used by Scriptable. | |
// These must be at the very top of the file. Do not edit. | |
// icon-color: gray; icon-glyph: vector-square; | |
// script : PanoramaImageSplit.js | |
// version : 1.0.0 | |
// description: Splits Panorama Images into multiple for InstaStories | |
// author : @wolfposd | |
// date : 2022-03-17 | |
let image = await Photos.fromLibrary(); | |
let splitDimensions = calculateSplits(image); | |
if(splitDimensions) | |
performSplits(image, splitDimensions) | |
Script.complete(); | |
function calculateSplits(img) { | |
const ratio = 0.5625; | |
// ratio based on instagram story 1080 x 1920 = 0.5625 | |
let w = img.size.width; | |
let h = img.size.height; | |
console.log(w + " x " + h); | |
if(h > w) { | |
showAlert("Dimension error", "Image width is smaller than height"); | |
return; | |
} | |
let desiredWidth = h * ratio; | |
let divisions = w / desiredWidth; | |
//console.log("desiredWidth " + desiredWidth); | |
//console.log(w / desiredWidth); | |
//console.log("divisions " + divisions); | |
let offset = 0.25 * Math.abs(desiredWidth - (w / Math.floor(divisions)) ); | |
//console.log("offset: " + offset); | |
let result = []; | |
for(var i = 0 ; i < divisions; i++) { | |
let s; | |
if( i == 0) { | |
s = {"start" : 0, "end" : Math.floor(desiredWidth)}; | |
} | |
else { | |
let start = (i * desiredWidth) - offset; | |
s = {"start" : Math.floor(start), "end" : Math.floor(start + desiredWidth)}; | |
} | |
result.push(s); | |
} | |
return result; | |
} | |
function performSplits(image, splitDimensions) { | |
console.log("Starting splits " + splitDimensions.size); | |
const targetHeight = image.size.height; | |
const imageWidth = image.size.width; | |
for(var split of splitDimensions) { | |
let ctx = new DrawContext(); | |
let targetWidth = split.end - split.start; | |
ctx.size = new Size(targetWidth, targetHeight); | |
let rect = new Rect(-1 * split.start, 0, imageWidth, targetHeight ); | |
//console.log("Rect:" + JSON.stringify(rect)); | |
ctx.drawImageInRect(image, rect); | |
let splitImage = ctx.getImage(); | |
Photos.save(splitImage); | |
} | |
showAlert("Done", "Created " + splitDimensions.length + " photos"); | |
} | |
function showAlert(title, text) { | |
let alert = new Alert(); | |
alert.title = title; | |
alert.message = text; | |
alert.present(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment