I need to convert a PNG file to Base64 data so that I can add it to a JSON object, using JXA (JavaScript Application Scripting).
JXA is limited compared to regular JavaScript so I can't immediately use functions from FileReader, etc.
From what I've read, there is no way that I know how to do this without using Objective-C/Cocoa (which I only started reading about today for this task).
I found the following code in another post:
NSArray *keys = [NSArray arrayWithObject:@"NSImageCompressionFactor"];
NSArray *objects = [NSArray arrayWithObject:@"1.0"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSImage *image = [[NSImage alloc] initWithContentsOfFile:[imageField stringValue]];
NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithData:[image TIFFRepresentation]];
NSData *tiff_data = [imageRep representationUsingType:NSPNGFileType properties:dictionary];
NSString *base64 = [tiff_data encodeBase64WithNewlines:NO];
I believe it is pertinent to what I am trying to do- does anybody know how I can bridge this method to use it in JXA?
I have been reading over the JXA Cookbook's section on Syntax for calling ObjC functions, but I am having difficulty understanding it... this is all that I have come up with so far:
var desktopString = app.pathTo("desktop").toString()
var file = `${desktopString}/test.png`
ObjC.import("Cocoa");
var image = $.NSImage.alloc.initWithContentsOfFile(file)
var imageRep = $.NSBitmapImageRep.alloc.initWithData(image)
But I don't know how to proceed- I am thrown off by:
- The whole initial NSArray/NSDictionary part
- TIFFRepresentation (Do I need it? Where do I put it?)
- NSData *tiff_data = [imageRep representationUsingType:NSPNGFileType properties:dictionary]; (There's no alloc! Why is dictionary needed?)
- NSString *base64 = [tiff_data encodeBase64WithNewlines:NO]; (Again, no alloc.)
I would be very appreciative if somebody could point me in the right direction / give me a few pointers on how I can accomplish what I am trying to do.
Thank you in advance!