gpt4 book ai didi

objective-c - 如何在 Cocoa 应用程序中设置导出的 JPEG 图像的每英寸像素数?

转载 作者:行者123 更新时间:2023-12-03 16:27:15 29 4
gpt4 key购买 nike

我有一个 Cocoa Mac 图像编辑应用程序,可以让用户导出 JPEG 图像。我当前正在使用以下代码将这些图像导出为 JPEG 文件:

//this is user specified
NSInteger resolution;

NSImage* savedImage = [[NSImage alloc] initWithSize:NSMakeSize(600, 600)];
[savedImage lockFocus];
//draw here
[savedImage unlockFocus];

NSBitmapImageRep* savedImageBitmapRep = [NSBitmapImageRep imageRepWithData:[savedImage TIFFRepresentationUsingCompression:NSTIFFCompressionNone factor:1.0]];

NSDictionary* properties = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:1.0], NSImageCompressionFactor, nil];

//holds the jpeg file
NSData * imageData = nil;
imageData = [savedImageBitmapRep representationUsingType:NSJPEGFileType properties:properties];

但是,我希望用户能够提供此 JPEG 图像的每英寸像素数(就像在 Photoshop 的导出选项中一样)。我需要在上面的代码中修改什么来调整导出的 JPEG 的该值?

最佳答案

我找不到使用 NSImage API 执行此操作的方法,但 CGImage 可以通过设置 kCGImagePropertyDPIHeight/Width 来实现。

我还设置了 kCGImageDestinationLossyCompressionQuality,我认为它与 NSImageCompressionFactor 相同。

//this is user specified
NSInteger resolution = 100;

NSImage* savedImage = [[NSImage alloc] initWithSize:NSMakeSize(600, 600)];
[savedImage lockFocus];
//draw here
[savedImage unlockFocus];

NSBitmapImageRep* savedImageBitmapRep = [NSBitmapImageRep imageRepWithData:[savedImage TIFFRepresentationUsingCompression:NSTIFFCompressionNone factor:1.0]];

NSDictionary* properties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:1.0], kCGImageDestinationLossyCompressionQuality,
[NSNumber numberWithInteger:resolution], kCGImagePropertyDPIHeight,
[NSNumber numberWithInteger:resolution], kCGImagePropertyDPIWidth,
nil];

NSMutableData* imageData = [NSMutableData data];
CGImageDestinationRef imageDest = CGImageDestinationCreateWithData((CFMutableDataRef) imageData, kUTTypeJPEG, 1, NULL);
CGImageDestinationAddImage(imageDest, [savedImageBitmapRep CGImage], (CFDictionaryRef) properties);
CGImageDestinationFinalize(imageDest);

// Do something with imageData
if (![imageData writeToFile:[@"~/Desktop/test.jpg" stringByExpandingTildeInPath] atomically:NO])
NSLog(@"Failed to write imageData");

关于objective-c - 如何在 Cocoa 应用程序中设置导出的 JPEG 图像的每英寸像素数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9231682/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com