NSImage 生成 PNG 格式图片

macOS

macOS 的工程里, 使用代码把 NSImage 转换成 PNG, 跟 iOS 上面不太一样.
macOS 下主要使用 AppKit 下的 NSBitmapImageRep 来进行转换, 代码如下:

NSImage *image = [[NSImage alloc] initWithContentsOfFile:@"filePath"];
CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)data, NULL);
CGImageRef cgimage = CGImageSourceCreateImageAtIndex(source, 0, NULL);
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithCGImage:cgimage];
// rep.size = CGSizeMake(width, width);
NSData *pngData = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
// pngData 写入磁盘 or 其他处理

支持的文件类型如下:

typedef NS_ENUM(NSUInteger, NSBitmapImageFileType) {
    NSBitmapImageFileTypeTIFF,
    NSBitmapImageFileTypeBMP,
    NSBitmapImageFileTypeGIF,
    NSBitmapImageFileTypeJPEG,
    NSBitmapImageFileTypePNG,
    NSBitmapImageFileTypeJPEG2000
};

缩放 NSImage:

NSImage *image = ...
// 缩放 image
NSImage *smallImage = [[NSImage alloc] initWithSize: CGSizeMake(width, width)];
[smallImage lockFocus];
[image setSize: CGSizeMake(width, width)];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[image drawAtPoint:NSZeroPoint fromRect:CGRectMake(0, 0, width, width) operation:NSCompositingOperationCopy fraction:1.0];
    [smallImage unlockFocus];

iOS

iOS 中, 主要是使用 UIKit 下的 UIImagePNGRepresentation() 方法, 直接就转换了, 比 macOS 下会简单不少.

UIImage *image = [UIImage imageNamed:@"name"];
NSData *pngData = UIImagePNGRepresentation(image);

不过, 我们最常见的就是这2个方法:

// return image as PNG. May return nil if image has no CGImageRef or invalid bitmap format
NSData * __nullable UIImagePNGRepresentation(UIImage * __nonnull image);                               

// return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compression is 0(most)..1(least)
NSData * __nullable UIImageJPEGRepresentation(UIImage * __nonnull image, CGFloat compressionQuality);  

你可能感兴趣的:(NSImage 生成 PNG 格式图片)