cocoa各种图片格式转换

来源:互联网 发布:汇率软件 编辑:程序博客网 时间:2024/05/21 07:10

具体下列格式png jpeg bmp gif tiff jpeg2000 pdf


PDF 要单独处理,其他的通过画图直接转即可。


1 画图 , 画一张红色图片

NSRect exportImageRect = NSZeroRect;

exportImageRect.size = NSMakeSize(100,100);


NSImage * result = [[[NSImage alloc] initWithSize:exportImageRect.size] autorelease];

[result lockFocus];

[[NSColor redColor] set];

[NSBezierPath fillRect:exportImageRect];

[result unlockFocus];


2,转换 除开pdf

,有些格式,对应的dictionary可以设置一些参数,压缩比什么的,gif的时长,一般的只用制定格式

- (void)saveImage:(NSImage *)image atPath:(NSString *)path {

    NSBitmapImageRep *newRep = [NSBitmapImageRep imageRepWithData:image.TIFFRepresentation];

    NSDictionary * properties = nil;

    

    NSBitmapImageFileType type = NSPNGFileType;

    if ([self.formatPopupButton.title isEqualToString:@"PNG"]) {

        type = NSPNGFileType;

    } else if ([self.formatPopupButton.title isEqualToString:@"JPEG"]) {

        type = NSJPEGFileType;

        properties = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:1.0] forKey:NSImageCompressionFactor];

    } else if ([self.formatPopupButton.title isEqualToString:@"BMP"]) {

        type = NSBMPFileType;

    } else if ([self.formatPopupButton.title isEqualToString:@"GIF"]) {

        type = NSGIFFileType;

    } else if ([self.formatPopupButton.title isEqualToString:@"TIFF"]) {

        type = NSTIFFFileType;

    } else if ([self.formatPopupButton.title isEqualToString:@"JPEG 2000"]) {

        type = NSJPEG2000FileType;

    }

    

    NSData *pngData = [newRep representationUsingType:type properties:properties];

    [pngData writeToFile:path atomically:YES];

}


3 ,转换成pdf

pdf一般是通过把图片设置到一个nsimageview控件里面,在从里面读pdf数据,然后写到文件


- (void)saveImageAsPDF:(NSImage *)image atPath:(NSString *)path {

    NSRect frame = NSZeroRect;

    frame.size = image.size;

    NSImageView * imageView = [[[NSImageView alloc] initWithFrame:frame] autorelease];

    

    [imageView setImage:image];

    

    NSData * pdfData = [imageView dataWithPDFInsideRect:frame];

    [pdfData writeToFile:path options:0 error:NULL];

}



0 0