NSImage,CFImage常规操作(转)

来源:互联网 发布:淘宝设置子账号名字 编辑:程序博客网 时间:2024/05/18 21:09

NSImage的一个扩展

作者:Codelif

    学习了Cocoa的图片制作,受益很多。知道了图片是怎么画出来的。上层原理。可以对图片的图层操作,如添加一个图层,删除图层,图片的混合,图片的缩放,矢量图图的制作,把字符串图片化,制作pdf的一些原理等。

  1. //
  2. //  NSImage+ZCPanel.h
  3. //  Flected
  4. //
  5. //  Created by zhuzhichao on 08-12-11.
  6. //  Copyright 2008 __MyCompanyName__. All rights reserved.
  7. //
  8. #import <Cocoa/Cocoa.h>
  9. #import "CTGradient.h"
  10. #define MAX_PIXEL_SIZE   600*800
  11. #define PIC_WIDTH  800
  12. #define PIC_HEIGHT 600
  13. //Picture fram
  14. /*
  15.    NSBMPFileType,
  16.    NSGIFFileType,
  17.    NSJPEGFileType,
  18.    NSPNGFileType,
  19.    NSJPEG2000FileType*/
  20. @interface NSImage (ZCPanel)
  21. + (NSImage *) prettyGradientImage:(NSSize)gradientSize;  // Generates a 256 by 256 pixel image with a complicated gradient in it.
  22. + (NSImage *) reflectedImage:(NSImage *)sourceImage amountReflected:(float)fraction;
  23. + (NSImage *) createScalesImage:(NSImage *)sourceImage flipFlag:(BOOL)bFlip amountReflected:(float)fraction;
  24. + (NSImage *) rotateImage:(NSImage*)sourceImage byDegrees:(float)deg;
  25. + (NSImage *) imageFromCGImageRef:(CGImageRef)image; //FROME CGImageRef to NSImage
  26. - (CGImageRef) nsImageToCGImageRef;//FROME  NSImage to CGImageRef
  27. - (BOOL) setSmoothingEffect; //Set smoothing effect
  28. - (BOOL) saveImage:(NSImage*)image 
  29.          saveType:(NSBitmapImageFileType)storageType
  30.          properties:(NSDictionary *)properties
  31.          ToTarget:(NSString *) targePath;
  32.          
  33. - (CGImageRef)thumbnailForFile: (NSString*)name atPath: (NSString*)filePath;
  34. @end
  35. //
  36. //  AppController+ZCBundImage.m
  37. //  Flected
  38. //
  39. //  Created by zhuzhichao on 08-12-11.
  40. //  Copyright 2008 __MyCompanyName__. All rights reserved.
  41. //
  42. #import "NSImage+ZCPanel.h"
  43. float distance(NSPoint aPoint);
  44. enum pixelComponents { red, green, blue, alpha };
  45. #define PI 3.14159265358979323846264338327950288
  46. @implementation NSImage (ZCPanel)
  47. ////倒立,深度
  48. + (NSImage *)reflectedImage:(NSImage *)sourceImage amountReflected:(float)fraction
  49. {
  50.     NSImage *reflection = [[NSImage alloc] initWithSize:[sourceImage size]];
  51.     [reflection setFlipped:YES];
  52.     [reflection lockFocus];
  53.     CTGradient *fade = [CTGradient gradientWithBeginningColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.5] endingColor:[NSColor clearColor]];
  54.     [fade fillRect:NSMakeRect(0, 0, [sourceImage size].width, [sourceImage size].height*fraction) angle:90.0];  
  55.     [sourceImage drawAtPoint:NSMakePoint(0,0) fromRect:NSZeroRect operation:NSCompositeSourceIn fraction:1.0];
  56.     [reflection unlockFocus];
  57.     return [reflection autorelease];
  58. }
  59. //缩放到目的大小,太小了不缩放添加背景
  60. + (NSImage *)createScalesImage:(NSImage *)sourceImage flipFlag:(BOOL)bFlip amountReflected:(float)fraction
  61. {
  62.     //set flipped
  63.     [sourceImage setScalesWhenResized:YES];
  64.     if(bFlip)
  65.     {
  66.         [sourceImage setFlipped:YES];
  67.     }
  68.     
  69.     //source picture size
  70.     NSSize srcSize = [sourceImage size];
  71.     unsigned int uiWidth= srcSize.width;
  72.     unsigned int uiHeight= srcSize.height;
  73.     
  74.     //target bg picture size
  75.     unsigned int bgWidth = PIC_WIDTH;
  76.     unsigned int bgHeight = PIC_HEIGHT;
  77.     NSSize tarSize =NSMakeSize(bgWidth, bgHeight);
  78.     
  79.     if(uiWidth>=bgWidth && uiHeight >= bgHeight)
  80.     {
  81.         [sourceImage setSize:tarSize];
  82.         return [[sourceImage copy] autorelease];
  83.     }
  84.     if(uiWidth>bgWidth && uiHeight < bgHeight)
  85.     {
  86.         [sourceImage setSize:tarSize];
  87.         
  88.         //target bg picture
  89.         NSImage *targetImage = [[NSImage alloc] initWithSize:tarSize];
  90.         [targetImage lockFocus];
  91.         //fill target bg picture,using white color
  92.         [[NSColor whiteColor] set];
  93.         NSRectFill(NSMakeRect(0,0, bgWidth, bgHeight*fraction));
  94.         
  95.         //draw
  96.         [sourceImage drawAtPoint:NSMakePoint(0,(bgHeight - uiHeight)*0.5) fromRect:NSZeroRect operation:NSCompositeSourceIn fraction:1.0];
  97.         [targetImage unlockFocus];
  98.         return [targetImage autorelease];
  99.     }
  100.     if(uiWidth<bgWidth && uiHeight >bgHeight)
  101.     {
  102.         [sourceImage setSize:tarSize];
  103.         
  104.         //target bg picture
  105.         NSImage *targetImage = [[NSImage alloc] initWithSize:tarSize];
  106.         [targetImage lockFocus];
  107.         //fill target bg picture,using white color
  108.         [[NSColor whiteColor] set];
  109.         NSRectFill(NSMakeRect(0, 0, bgWidth, bgWidth*fraction));
  110.         
  111.         //draw
  112.         [sourceImage drawAtPoint:NSMakePoint((bgWidth- uiWidth)*0.5, 0) fromRect:NSZeroRect operation:NSCompositeSourceIn fraction:1.0];
  113.         [targetImage unlockFocus];
  114.         return [targetImage autorelease];
  115.     }
  116.     else
  117.     //(uiWidth<bgWidth && uiHeight < bgHeight)
  118.     {
  119.         //[sourceImage setSize:tarSize];
  120.         //target bg picture
  121.         NSImage *targetImage = [[NSImage alloc] initWithSize:tarSize];
  122.         [targetImage lockFocus];
  123.         //fill target bg picture,using white color
  124.         [[NSColor whiteColor] set];
  125.         NSRectFill(NSMakeRect(0, 0, bgWidth, bgWidth*fraction));
  126.         
  127.         //draw
  128.         [sourceImage drawAtPoint:NSMakePoint((bgWidth - uiWidth)*0.5, (bgHeight - uiHeight)*0.5) fromRect:NSZeroRect operation:NSCompositeSourceIn fraction:1.0];
  129.         [targetImage unlockFocus];
  130.         return [targetImage autorelease];
  131.     }
  132. }
  133. //按照图片的中心旋转90.180.270,360度
  134. + (NSImage *) rotateImage:(NSImage*)sourceImage byDegrees:(float)deg
  135. {
  136.     NSSize srcsize= [sourceImage size];
  137.     float srcw = srcsize.width;
  138.     float srch= srcsize.height;
  139.     float newdeg = 0;
  140.     //旋转弧度
  141.     //double ratain = ((deg/180) * PI);
  142.     NSRect r1;
  143.     if(0< deg && deg <=90)
  144.     {
  145.         r1 = NSMakeRect(0.5*(srcw -srch), 0.5*(srch-srcw), srch, srcw);
  146.         newdeg = 90.0;
  147.     }
  148.     if(90< deg && deg <=180)
  149.     {
  150.         r1 = NSMakeRect(0, 0, srcw, srch);
  151.         newdeg = 180.0;
  152.     }
  153.     if(180< deg && deg <=270)
  154.     {
  155.         r1 = NSMakeRect(0.5*(srcw -srch), 0.5*(srch-srcw), srch, srcw);
  156.         newdeg = 270.0;
  157.     }
  158.     if(270< deg && deg <=360)
  159.     {
  160.         r1 = NSMakeRect(0, 0, srch, srcw);
  161.         newdeg = 360;
  162.     }
  163.     
  164.     //draw new image
  165.     NSImage *rotated = [[NSImage alloc] initWithSize:[sourceImage size]];
  166.     [rotated lockFocus];
  167.     NSAffineTransform *transform = [NSAffineTransform transform];
  168.     [transform translateXBy:(0.5*srcw) yBy: (0.5*srch)];  //按中心图片旋转
  169.     [transform rotateByDegrees:newdeg];                   //旋转度数,rotateByRadians:使用弧度
  170.     [transform translateXBy:(-0.5*srcw) yBy: (-0.5*srch)];
  171.     [transform concat];
  172.     [[sourceImage bestRepresentationForDevice: nil] drawInRect: r1];//矩形内画图
  173.     
  174.     //[sourceImage drawInRect:r1 fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
  175.     //[sourceImage drawAtPoint:arge/*NSZeroPoint*/ fromRect:NSMakeRect(arge.x, arge.y,ww ,wh)/*NSZeroRect*/ operation:NSCompositeCopy fraction:1.0];
  176.     [rotated unlockFocus];
  177.     
  178.     return [rotated autorelease];
  179. //save image to file
  180. - (BOOL)saveImage:(NSImage*)image                      //source image
  181.          saveType:(NSBitmapImageFileType)storageType   //save type "NSJPEGFileType"
  182.          properties:(NSDictionary *)properties         //properties "NSImageCompressionFactor = (NSNumber)0.8"
  183.          ToTarget:(NSString *) targePath               //save path
  184. {
  185.     NSData *tempdata;
  186.     NSBitmapImageRep *srcImageRep;
  187.     BOOL reflag = NO;
  188.     [image lockFocus];
  189.     srcImageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
  190.     tempdata = [srcImageRep representationUsingType:storageType properties:properties];
  191.     reflag = [tempdata writeToFile:targePath atomically:YES];
  192.     [image unlockFocus];
  193.     return reflag;
  194. }
  195. // ---------------------------------------------------------------------------------------------------------------------
  196. - (CGImageRef)thumbnailForFile: (NSString*)name
  197.                         atPath: (NSString*)filePath
  198. {
  199.     // use ImageIO to get a thumbnail for a file at a given path
  200.     CGImageSourceRef    isr = NULL;
  201.     NSString *          path = [filePath stringByExpandingTildeInPath];
  202.     CGImageRef          image = NULL;
  203.     
  204.   //  path = [path stringByAppendingPathComponent: name];
  205.     
  206.     // create the CGImageSourceRef
  207.     isr = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath: path], NULL);
  208.     if (isr)
  209.     {
  210.         // create a thumbnail:
  211.         // - specify max pixel size
  212.         // - create the thumbnail with honoring the EXIF orientation flag (correct transform)
  213.         // - always create the thumbnail from the full image (ignore the thumbnail that may be embedded in the image -
  214.         //                                                  reason: our MAX_ICON_SIZE is larger than existing thumbnail)
  215.         image = CGImageSourceCreateThumbnailAtIndex (isr, 0, (CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
  216.             [NSNumber numberWithInt: MAX_PIXEL_SIZE],  kCGImageSourceThumbnailMaxPixelSize,
  217.             (id)kCFBooleanTrue,                       kCGImageSourceCreateThumbnailWithTransform,
  218.             (id)kCFBooleanTrue,                       kCGImageSourceCreateThumbnailFromImageAlways,
  219.             NULL] );
  220.         
  221.         CFRelease(isr);
  222.     }
  223.     return image;
  224. }
  225. + (NSImage*) imageFromCGImageRef:(CGImageRef)image
  226. {
  227.     NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
  228.     CGContextRef imageContext = nil;
  229.     NSImage* newImage = nil;
  230.     // Get the image dimensions.
  231.     imageRect.size.height = CGImageGetHeight(image);
  232.     imageRect.size.width = CGImageGetWidth(image);
  233.     // Create a new image to receive the Quartz image data.
  234.     newImage = [[[NSImage alloc] initWithSize:imageRect.size] autorelease];
  235.     [newImage lockFocus];
  236.     // Get the Quartz context and draw.
  237.     imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
  238.     CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
  239.     [newImage unlockFocus];
  240.     return newImage;
  241. }
  242. - (CGImageRef)nsImageToCGImageRef//:(NSImage*)image;
  243. {
  244.     NSData * imageData = [self TIFFRepresentation];
  245.     CGImageRef imageRef;
  246.     if(imageData)
  247.     {
  248.         CGImageSourceRef imageSource =
  249.          CGImageSourceCreateWithData(
  250.                             (CFDataRef)imageData,  NULL);
  251.         imageRef = CGImageSourceCreateImageAtIndex(
  252.                                imageSource, 0, NULL);
  253.     }
  254.     return imageRef;
  255. }
  256. //Set smoothing effect
  257. - (BOOL)setSmoothingEffect
  258. {
  259.     NSBitmapImageRep *rep = [[self representations] objectAtIndex: 0];
  260.     NSSize size = NSMakeSize ([rep pixelsWide], [rep pixelsHigh]);
  261.     if(size.width >0 && size.height>0)
  262.     {
  263.         [self setSize: size];
  264.         return YES;
  265.     }
  266.     return NO;
  267. }
  268.  // Generates a 256 by 256 pixel image with a complicated gradient in it.
  269. + (NSImage *) prettyGradientImage:(NSSize)gradientSize
  270. {
  271.     NSImage *newImage = [[self alloc] initWithSize:gradientSize];  // In this case, the pixel dimensions match the image size.
  272.     int pixelsWide = gradientSize.width;
  273.     int pixelsHigh = gradientSize.height;    
  274.     
  275.     NSBitmapImageRep *bitmapRep = 
  276.         [[NSBitmapImageRep alloc] 
  277.         initWithBitmapDataPlanes: nil  // Nil pointer makes the kit allocate the pixel buffer for us.
  278.         pixelsWide: pixelsWide  // The compiler will convert these to integers, but I just wanted to  make it quite explicit
  279.         pixelsHigh: pixelsHigh //
  280.         bitsPerSample: 8
  281.         samplesPerPixel: 4  // Four samples, that is: RGBA
  282.         hasAlpha: YES
  283.         isPlanar: NO  // The math can be simpler with planar images, but performance suffers..
  284.         colorSpaceName: NSCalibratedRGBColorSpace  // A calibrated color space gets us ColorSync for free.
  285.         bytesPerRow: 0     // Passing zero means "you figure it out."
  286.         bitsPerPixel: 32];  // This must agree with bitsPerSample and samplesPerPixel.
  287.   
  288.     unsigned char *imageBytes = [bitmapRep bitmapData];  // -bitmapData returns a void*, not an NSData object ;-)
  289.   
  290.     int row = pixelsHigh;
  291.     while(row--)
  292.     {
  293.         int col = pixelsWide;
  294.         while(col--) 
  295.         {
  296.             int 
  297.             pixelIndex = 4 * (row * pixelsWide + col);
  298.             imageBytes[pixelIndex + red] = rint(fmod(distance(NSMakePoint(col/1.5,(255-row)/1.5)),255.0));  //red
  299.             imageBytes[pixelIndex + green] = rint(fmod(distance(NSMakePoint(col/1.5, row/1.5)),255.0));  // green
  300.             imageBytes[pixelIndex + blue] = rint(fmod(distance(NSMakePoint((255-col)/1.5,(255-row)/1.5)),255.0));  // blue
  301.             imageBytes[pixelIndex + alpha] = 255;  // Not doing anything tricky with the Alpha value here...
  302.         }
  303.     }
  304.     [newImage addRepresentation:bitmapRep];
  305.     return [newImage autorelease];
  306. }
  307. @end
  308. float distance(NSPoint aPoint)  // Stole this from some guy named Pythagoras..  Returns the distance of aPoint from the origin.
  309. {
  310.   return sqrt(aPoint.x * aPoint.x + aPoint.y *aPoint.y);
  311. }
  312. //open selecter file panel
  313. /*static NSArray* openImageFiles()
  314.     // Get a list of extensions to filter in our NSOpenPanel.
  315.     NSOpenPanel* panel = [NSOpenPanel openPanel];
  316.     [panel setCanChooseDirectories:YES];    // The user can choose a folder; images in the folder are added recursively.
  317.     [panel setCanChooseFiles:YES];
  318.     [panel setAllowsMultipleSelection:YES];
  319.     if ([panel runModalForTypes:[NSImage imageUnfilteredFileTypes]] == NSOKButton)
  320.         return [panel filenames];
  321.     return nil;
  322. }*/
原创粉丝点击