Skip to content

Instantly share code, notes, and snippets.

@rok-git
Created January 12, 2022 01:51
Show Gist options
  • Save rok-git/cb077fdab6db848995c274f05b45f812 to your computer and use it in GitHub Desktop.
Save rok-git/cb077fdab6db848995c274f05b45f812 to your computer and use it in GitHub Desktop.
Sample of PhotoKit on macOS.
//To Compile: cc -fobjc-arc -framework Cocoa -framework Photos random256x256.m -o random256x256
#import <Cocoa/Cocoa.h>
#import <Photos/Photos.h>
#include <stdlib.h>
int main()
{
@autoreleasepool{
PHFetchResult *assets = [PHAsset fetchAssetsWithMediaType: PHAssetMediaTypeImage options: nil];
NSUInteger idx = arc4random() % assets.count;
PHAsset *asset = assets[idx];
PHImageManager *phiManager = [PHImageManager defaultManager];
PHImageRequestOptions *opt = [[PHImageRequestOptions alloc] init];
opt.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
opt.resizeMode = PHImageRequestOptionsResizeModeExact;
// PHImageRequestOption's synchronous blocks the thread until data is ready.
// So we don't need RunLoop.
// (If opt.synchronous is NO (default), we need RunLoop to wait until resultHandler completes.)
opt.synchronous = YES;
[phiManager requestImageForAsset: asset
targetSize: CGSizeMake(256,256)
contentMode: PHImageContentModeAspectFill
options: opt
resultHandler: ^(NSImage *resultImage, NSDictionary *info){
NSBitmapImageRep *bitmap = [NSBitmapImageRep imageRepWithData: [resultImage TIFFRepresentation]];
NSData *jpegData = [bitmap representationUsingType: NSBitmapImageFileTypeJPEG properties: [NSDictionary dictionary]];
NSFileHandle *fh = [NSFileHandle fileHandleWithStandardOutput];
[fh writeData: jpegData];
}
];
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment