图片数据类型转换 NSImage、CIImage、CGImageRef

不知道苹果怎么想的,七八种图片数据类型格式,转换起来非常麻烦。本文摘抄了几种转换的方法,供参考。 将NSImage转换为CIImage #import QuartzCore/CIFilter.h // convert NSImage to bitmap NSImage *

不知道苹果怎么想的,七八种图片数据类型格式,转换起来非常麻烦。本文摘抄了几种转换的方法,供参考。

将NSImage转换为CIImage

 

 

#import <QuartzCore/CIFilter.h>

 

// convert NSImage to bitmap

NSImage * myImage  = [self currentImage];

NSData  * tiffData = [myImage TIFFRepresentation];

NSBitmapImageRep * bitmap;

bitmap = [NSBitmapImageRep imageRepWithData:tiffData];

 

// create CIImage from bitmap

CIImage * ciImage = [[CIImage alloc] initWithBitmapImageRep:bitmap];

 

// create affine transform to flip CIImage

NSAffineTransform *affineTransform = [NSAffineTransform transform];

[affineTransform translateXBy:0 yBy:128];

[affineTransform scaleXBy:1 yBy:-1];

 

// create CIFilter with embedded affine transform

CIFilter *transform = [CIFilter filterWithName:@"CIAffineTransform"];

[transform setValue:ciImage forKey:@"inputImage"];

[transform setValue:affineTransform forKey:@"inputTransform"];

 

// get the new CIImage, flipped and ready to serve

CIImage * result = [transform valueForKey:@"outputImage"];

 

// draw to view

[result drawAtPoint: NSMakePoint ( 0,0 )

           fromRect: NSMakeRect  ( 0,0,128,128 )


          operation: NSCompositeSourceOver

           fraction: 1.0];

 

// cleanup

[ciImage release];

 

将CGImageRef转换为NSImage *

 

 

- (NSImage*) imageFromCGImageRef:(CGImageRef)image

 

{

 

    NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);

 

    CGContextRef imageContext = nil;

 

    NSImage* newImage = nil;

 

 

 

    // Get the image dimensions.

 

    imageRect.size.height = CGImageGetHeight(image);

 

    imageRect.size.width = CGImageGetWidth(image);

 

 

 

    // Create a new image to receive the Quartz image data.

 

    newImage = [[[NSImage alloc] initWithSize:imageRect.size] autorelease];

 

    [newImage lockFocus];



    // Get the Quartz context and draw.

 

    imageContext = (CGContextRef)[[NSGraphicsContext currentContext]

 

                                         graphicsPort];

 

    CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);

 

    [newImage unlockFocus];

 

 

 

    return newImage;

 

}

 

将NSImage *转换为CGImageRef 

 

 

- (CGImageRef)nsImageToCGImageRef:(NSImage*)image;

{

    NSData * imageData = [image TIFFRepresentation];

    CGImageRef imageRef;

    if(imageData)

    {

        CGImageSourceRef imageSource = 

                  CGImageSourceCreateWithData(

                            (CFDataRef)imageData,  NULL);

 

        imageRef = CGImageSourceCreateImageAtIndex(

                               imageSource, 0, NULL);

    }



    return imageRef;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值