Reputation: 113
I'm making a macOS app, starting from a IOSapp. In the iOS app, the screenshot is first created and then saved by this method:
void Bridge::SaveScreenshot(unsigned char * img, ssize_t size, int width, int height) {
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(img,
width,
height,
8,
width * 4,
colorSpace,
kCGImageAlphaPremultipliedLast );
CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
UIImage* rawImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
UIImageWriteToSavedPhotosAlbum(rawImage, nil, nil, nil);
CGColorSpaceRelease(colorSpace);
CGContextRelease(ctx);
The lines that gives me error are:
UIImage* rawImage = [UIImage imageWithCGImage:imageRef];
...
UIImageWriteToSavedPhotosAlbum(rawImage, nil, nil, nil);
I don't know how to change it to make it save the image on Mac. Could someone tell me how to change them or what I have to use to save images on the machine from a macOS app? Thks for reading and if you want answer.
Upvotes: 0
Views: 276
Reputation: 634
In MacOs image is saved as NSImage. So, you have convert UImage to NSData then NSData to NSImage and save the following way.
extension NSImage {
func writeToFile(file: String, automatically: Bool, usingType type: NSBitmapImageFileType) -> Bool {
let properties = [NSImageCompressionFactor: 1.0]
guard
let imageData = TIFFRepresentation,
imageRep = NSBitmapImageRep(data: imageData),
fileData = imageRep.representationUsingType(type, properties: properties) else {
return false
}
return fileData.writeToFile(file, atomically: atomically)
}
Usage:
let yourFilePath = ...path to save
yourImage.writeToFile(yourFilePath, automatically: true, usingType: .NSPNGFileType) // as png
yourImage.writeToFile(yourFilePath, automatically: true, usingType: .NSJPEGFileType) // as jpg
Upvotes: 1