cocoa 几个常用的图片处理函数

cocoa 几个常用的图片处理函数,第1张

概述.h文件 #import <Cocoa/Cocoa.h> #import "NSImage+Conversion.h" void releaseMyContextData(CGContextRef content); CGContextRef MyCreateBitmapContext (int pixelsWide, int pixelsHigh); //判断文件是否存在 BOOL      

.h文件

#import <Cocoa/Cocoa.h>

#import "NSImage+Conversion.h"


voID releaseMyContextData(CGContextRef content);

CGContextRef MyCreateBitmapContext (int pixelsWIDe,int pixelsHigh);


//判断文件是否存在

BOol       pathIsAfile(Nsstring *path);


//通过路径加载NSImage 这样写之后 不能象imagename方法那样可以自动识别大图还是小图(Retina)

NSImage*   loadNSImageWithname(Nsstring * path);


//通过路径加载CGImageRef

CGImageRef createCGImageWithname(Nsstring * path);


//NSImage to CGImage

CGImageRef createCGImageRefFromNSImage(NSImage* image);


//把一张简单的黑白图对象转成一张mask图片对象

CGImageRef createMaskWithImage(CGImageRef image);


//这个是苹果官方的标准写法

NSImage* createNSImageFromCGImageRef2(CGImageRef image);

//CGImage to NSImage

NSImage* createNSImageFromCGImageRef(CGImageRef image);


//缩放图片 按宽高 (既新的返回图片的宽变成wIDth 高变成height)

CGImageRef createScaleImageByXY(CGImageRef image,float wIDth,float height);


//缩放图片 按比例

CGImageRef createScaleImageByRatio(NSImage *image,float fratio);


BOol saveImagepng(CGImageRef imageRef,Nsstring *strpath);

BOol saveImagejpg(CGImageRef imageRef,Nsstring *strpath);



.m文件

#import "UtilitIEs.h"


voID releaseMyContextData(CGContextRef content){

    voID *imgdata =CGBitmapContextGetData(content);

    CGContextRelease(content);

    if (imgdata) {

        free(imgdata);

    }

}


CGContextRef MyCreateBitmapContext (int pixelsWIDe,

int pixelsHigh)

{

CGContextRef context = NulL;

CGcolorSpaceRef colorSpace;

glubyte *bitmapData;

int bitmapByteCount;

int bitmapBytesPerRow;

bitmapBytesPerRow = (pixelsWIDe * 4);

bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);

colorSpace = CGcolorSpaceCreateWithname(kCGcolorSpaceGenericRGB);//CGcolorSpaceCreateDeviceRGB();//

    

    //z这里初始化用malloccalloc都可以 (注意:malloc只能分配内存 初始化所分配的内存空间 calloc则可以)

    //在此需要特别注意的是  第二个参数传0进去  如果传比较大的数值进去的话  则会内存泄漏 比如传8之类的就会出现大的泄漏问题

    /*如果调用成功,函数malloc()和函数calloc()

     将返回所分配的内存空间的首地址。

     函数malloc()和函数calloc()的主要区别是前

     者不能初始化所分配的内存空间,而后者能。如

     果由malloc()函数分配的内存空间原来没有被

     使用过,则其中的每一位可能都是0;反之,如果

     这部分内存曾经被分配过,则其中可能遗留有各

     种各样的数据。也就是说,使用malloc()函数

     的程序开始时(内存空间还没有被重新分配)

     正常进行,但经过一段时间(内存空间还已经被

     重新分配)可能会出现问题

     函数calloc()会将所分配的内存空间中的每一

     位都初始化为零,也就是说,如果你是为字符类

     型或整数类型的元素分配内存,那麽这些元素将

     保证会被初始化为0;如果你是为指针类型的元

     素分配内存,那麽这些元素通常会被初始化为空

     指针;如果你为实型数据分配内存,则这些元素

     会被初始化为浮点型的零*/

    //NSLog(@"%lu",sizeof(glubyte));

bitmapData = (glubyte*)calloc(bitmapByteCount,sizeof(glubyte));//or malloc(bitmapByteCount);//

    

if (bitmapData == NulL) {

fprintf(stderr,"Memory not allocated!");

return NulL;

}

    

context = CGBitmapContextCreate(bitmapData, 

pixelsWIDe, 

pixelsHigh, 

8

bitmapBytesPerRow,

colorSpace, 

kCGImageAlphaPremultiplIEdLast);

if (context == NulL) {

free(bitmapData);

);

return NulL;

}

CGcolorSpaceRelease(colorSpace);

return context;

}


//---------------------------------------------------------------------------------

// createCGImageWithname:

//

// simple utility function that create an image from a name by looking into the main bundle

//---------------------------------------------------------------------------------

CGImageRef createCGImageWithname(Nsstring * path)

{

    CGImageRef image = NulL;

    CFURLRef url = (CFURLRef) [NSURL fileURLWithPath: path];

    CGImageSourceRef src = CGImageSourceCreateWithURL(url,NulL);

    if( src ) {

        //NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys: (ID)kcfBooleanFalse,(ID)kCGImageSourceShouldCache,(ID)kcfBooleanTrue,(ID)kCGImageSourceShouldAllowfloat,nil];//[NSNumber numberWithBool:YES],(Nsstring *)kCGImageSourceCreatethumbnailFromImageIfAbsent,[NSNumber numberWithInt:360],(Nsstring *)kCGImageSourcethumbnailMaxPixelSize,nil];

        

        image = CGImageSourceCreateImageAtIndex(src,0,NulL);//(CFDictionaryRef)options);

        CFRelease(src);

        if(!image) NSLog(@"Warning: CGImageSourceCreateImageAtIndex Failed on file %@ (ptr size=%lu)",path,sizeof(voID*));

    }

    

    

    return image;

}


BOol       pathIsAfile(Nsstring *path){

    NSfileManager *fileManager = [NSfileManager defaultManager];

    BOol isDir,valID = [fileManager fileExistsAtPath:path isDirectory:&isDir];

    if (valID) {   

    }else{

        return NO;

    }

    return YES;

}

NSImage* loadNSImageWithname(Nsstring * path){

fileExistsAtPath:path isDirectory:&isDir];

    if (valID) {   

    }else{

        return nil;

    }

    if ([path isEqualToString:@""] || !path) {

        return nil;

    }

    CGImageRef img = createCGImageWithname(path);

    if (!img) {

        return nil;

    }

    NSImage *image = [[NSImage alloc] initWithCGImage:img];

    CFRelease(img);

    return [image autorelease];

    //return [NSImage imagenamed:path];

}


BOol saveImagepng(CGImageRef imageRef,Nsstring *strpath)

{

    Nsstring *finalPath = [Nsstring stringWithString:strpath];

    CFURLRef url = CFURLCreateWithfileSystemPath (

                                                  kcfAllocatorDefault,

                                                  (CFStringRef)finalPath,

                                                  kcfURLPOSIXPathStyle,

                                                  false);

    CGImageDestinationRef dest = CGImageDestinationCreateWithURL(url,CFSTR("public.png"),1,NulL);

    assert(dest);

    CGImageDestinationAddImage(dest,imageRef,NulL);

    assert(dest);

    if (dest == NulL) {

        NSLog(@"CGImageDestinationCreateWithURL Failed");

    }

    //NSLog(@"%@",dest);

    assert(CGImageDestinationFinalize(dest));

    

    //这三句话用来释放对象

    CFRelease(dest);

    //CGImageRelease(imageRef);

    CFRelease(url);

    return YES;

}


BOol saveImagejpg(CGImageRef imageRef,

                                                  false);

    CGImageDestinationRef dest = NulL;

        dest = CGImageDestinationCreateWithURL(url,CFSTR("public.jpeg"),NulL);

        

        assert(dest);

        

        cfmutabledictionaryRef  mSaveMetaAndOpts = CFDictionaryCreateMutable(nil, 0,

                                                                             &kcfTypeDictionaryKeyCallBacks,  &kcfTypeDictionaryValueCallBacks);

        CFDictionarySetValue(mSaveMetaAndOpts,kCGImageDestinationLossyCompressionQuality

                             [NSNumber numberWithfloat:0.8]);

        

        CGImageDestinationAddImage(dest,(CFDictionaryRef)mSaveMetaAndOpts);

        

        

        CFRelease(mSaveMetaAndOpts);

        

        //CGImageDestinationAddImage(dest,NulL);

        assert(dest);

        if (dest == NulL) {

            NSLog(@"CGImageDestinationCreateWithURL Failed");

        }

        //NSLog(@"%@",129)">         assert(CGImageDestinationFinalize(dest));

        

        //这三句话用来释放对象

        CFRelease(dest);

        //CGImageRelease(imageRef);

        //CFRetain(url);

        CFRelease(url);

    return YES;

}


    

CGImageRef createCGImageRefFromNSImage(NSImage* image)

{

    NSData *imageData;

    CGImageRef imageRef;

    @try {

        imageData = [image TIFFRepresentation];

        if (imageData) {

            CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData,NulL);

            NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:

                                     (ID)kcfBooleanFalse,(ID)kCGImageSourceShouldCache,

                                     (ID)kcfBooleanTrue,(ID)kCGImageSourceShouldAllowfloat,

                                     nil];

            

            //要用这个带option kCGImageSourceShouldCache指出不需要系统做cache *** 作 默认是会做的

            imageRef = CGImageSourceCreateImageAtIndex(imageSource,(CFDictionaryRef)options);

            CFRelease(imageSource);

            return imageRef;

        }else{

            return NulL;

        }

    }

    @catch (NSException *exception) {

        

    }

    @finally {

        

    }

    

    return NulL;

}


//这个是苹果官方的标准写法

NSImage* createNSImageFromCGImageRef2(CGImageRef image)

{

NSImage* newImage = nil;

#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5 

NSBitmAPImageRep* newRep = [[NSBitmAPImageRep alloc] initWithCGImage:image];

NSSize imageSize;

// Get the image dimensions. 

imageSize.height = CGImageGetHeight(image); 

imageSize.wIDth = CGImageGetWIDth(image);

newImage = [[NSImage alloc] initWithSize:imageSize]; 

[newImage addRepresentation:newRep];

[newRep release];

#else

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

CGContextRef imageContext = 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]; 

[newImage lockFocus];

// Get the Quartz context and draw. 

imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];

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

[newImage unlockFocus];

#endif

return newImage;//[newImage autorelease];

}

NSImage* createNSImageFromCGImageRef(CGImageRef image){

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

    CGContextRef imageContext = nil;

    NSImage *newImage = nil;

    //Get the image dimensions

    @try {

        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];

        [newImage lockFocus];

        

        //Get the Quartz context and draw

        imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];

        //CGContextSaveGState(imageContext);

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

        //CGContextRestoreGState(imageContext);

        [newImage unlockFocus];

        //CFRelease(imageContext);

        

    }

    @catch (NSException *exception) {

        

    }

    @finally {

        

    }

    

    return newImage;

}


CGImageRef createMaskWithImage(CGImageRef image)

{

    //NSAssert(image != NulL,@"The Foo pointer must not be NulL!");

    if (image == NulL) {

        return NulL;

    }

    

    @try {

        

        int mw = (int)CGImageGetWIDth(image);

        int mh = (int)CGImageGetHeight(image);

        //round bytesPerRow to the nearest 16 bytes,for performance's sake

        int bytesPerRow = (mw + 15)&0xfffffff0;

        //int bufferSize = bytesPerRow * mh;

        

        glubyte *imgdata = (glubyte*) calloc(mw * mh * 4,sizeof(glubyte));

        

        //the data will be 8 bits per pixel,no Alpha

        CGcolorSpaceRef cSpace = CGcolorSpaceCreateDeviceGray();//CGcolorSpaceCreateWithname(kCGcolorSpaceGenericRGB);

        CGContextRef content = CGBitmapContextCreate(imgdata,mw,mh,8,bytesPerRow,cSpace,

                                                     kCGImageAlphaNone);

        CGContextDrawImage(content, CGRectMake(0,mh),image);

        CGImageRef mask = CGBitmapContextCreateImage(content);

        CFRelease(cSpace);

        CGContextRelease(content);

        free(imgdata);

        

        return mask;

    }

    

    @catch (NSException *exception) {

    }

    @finally {

        

    }

    return  NulL;

}


CGImageRef createScaleImageByXY(CGImageRef image,float height) {

    CGContextRef content = MyCreateBitmapContext(wIDth,height);

    CGContextDrawImage(content,wIDth,height),image);

    CGImageRef img = CGBitmapContextCreateImage(content);

    

    releaseMyContextData(content);

    

    return img;

}


CGImageRef createScaleImageByRatio(NSImage *image,float fratio){

    NSData *imageData;

    imageData = [image TIFFRepresentation];

    if (imageData) {

        CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData,NulL);

        

        NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:

                                 // Ask ImageIO to create a thumbnail from the file's image data,if it can't find a suitable existing thumbnail image in the file.  We Could comment out the following line if only existing thumbnails were desired for some reason (maybe to favor performance over being guaranteed a complete set of thumbnails).

                                 [NSNumber numberWithBool:YES],(Nsstring *)kCGImageSourceCreatethumbnailFromImageIfAbsent,

                                 [NSNumber numberWithInt:[image size].wIDth*fratio],(Nsstring *)kCGImageSourcethumbnailMaxPixelSize,

                                 nil];

        CGImageRef thumbnail = CGImageSourceCreatethumbnailAtIndex(imageSource,(CFDictionaryRef)options);

        CFRelease(imageSource);

        return thumbnail;

    }

    

    return nil;

}

总结

以上是内存溢出为你收集整理的cocoa 几个常用图片处理函数全部内容,希望文章能够帮你解决cocoa 几个常用的图片处理函数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1053731.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存