微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

NSImage,CFImage常规操作转

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐