Skip to content

Instantly share code, notes, and snippets.

@mayoff
Created February 11, 2019 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayoff/0a049c4d9be9e4b5090329c49752f928 to your computer and use it in GitHub Desktop.
Save mayoff/0a049c4d9be9e4b5090329c49752f928 to your computer and use it in GitHub Desktop.
Set pHYs chunk (DPI) of PNG
@import AppKit;
@import ImageIO;
@import CoreServices;
#define fromCF (__bridge id)
#define toCF (__bridge CFTypeRef)
int main(int argc, const char * argv[]) {
@autoreleasepool {
CGRect rect = CGRectMake(0, 0, 100, 100);
NSImage *nsImage = [NSImage imageWithSize:rect.size flipped:NO drawingHandler:^BOOL(NSRect dstRect) {
[NSColor.whiteColor set];
NSRectFill(CGRectInfinite);
[NSColor.redColor set];
[[NSBezierPath bezierPathWithOvalInRect:CGRectInset(rect, 10, 10)] fill];
return YES;
}];
CGImageRef cgImage = [nsImage CGImageForProposedRect:&rect context:nil hints:nil];
NSURL *url = [NSURL fileURLWithPath:@"/tmp/test.png"];
CGImageDestinationRef dest = CGImageDestinationCreateWithURL(toCF url, kUTTypePNG, 1, nil);
NSDictionary<NSString *, id> *imageProperties = @{ fromCF kCGImagePropertyDPIHeight: @(17), fromCF kCGImagePropertyDPIWidth: @(19) };
CGImageDestinationAddImage(dest, cgImage, toCF imageProperties);
CGImageDestinationFinalize(dest);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment