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

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.         [[NSColor whiteColor] set];
  92.         NSRectFill(NSMakeRect(0, bgWidth*fraction));
  93. //draw
  94.         [sourceImage drawAtPoint:NSMakePoint((bgWidth- uiWidth)*0.5, 0) fromRect:NSZeroRect operation:NSCompositeSourceIn fraction:1.0];
  95.         [targetImage unlockFocus];
  96.         return [targetImage autorelease];
  97.     else
  98. //(uiWidth<bgWidth && uiHeight < bgHeight)
  99. //[sourceImage setSize:tarSize];
  100.         [sourceImage drawAtPoint:NSMakePoint((bgWidth - uiWidth)*0.5, (bgHeight - uiHeight)*0.5) fromRect:NSZeroRect operation:NSCompositeSourceIn fraction:1.0];
  101. //按照图片的中心旋转90.180.270,360度
  102. float)deg
  103.     NSSize srcsize= [sourceImage size];
  104.     float srcw = srcsize.width;
  105.     float srch= srcsize.height;
  106. float newdeg = 0;
  107. //旋转弧度
  108. //double ratain = ((deg/180) * PI);
  109.     NSRect r1;
  110.     if(0< deg && deg <=90)
  111.         r1 = NSMakeRect(0.5*(srcw -srch), 0.5*(srch-srcw), srch, srcw);
  112.         newdeg = 90.0;
  113.     if(90< deg && deg <=180)
  114.         r1 = NSMakeRect(0, srcw, srch);
  115.         newdeg = 180.0;
  116.     if(180< deg && deg <=270)
  117.         newdeg = 270.0;
  118.     if(270< deg && deg <=360)
  119.         newdeg = 360;
  120. //draw new image
  121.     NSImage *rotated = [[NSImage alloc] initWithSize:[sourceImage size]];
  122.     [rotated lockFocus];
  123.     NSAffineTransform *transform = [NSAffineTransform transform];
  124.     [transform translateXBy:(0.5*srcw) yBy: (0.5*srch)];  //按中心图片旋转
  125.     [transform rotateByDegrees:newdeg];                   //旋转度数,rotateByRadians:使用弧度
  126.     [transform translateXBy:(-0.5*srcw) yBy: (-0.5*srch)];
  127.     [transform concat];
  128.     [[sourceImage bestRepresentationForDevice: nil] drawInRect: r1];//矩形内画图
  129. //[sourceImage drawInRect:r1 fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
  130. //[sourceImage drawAtPoint:arge/*NSZeroPoint*/ fromRect:NSMakeRect(arge.x, arge.y,ww ,wh)/*NSZeroRect*/ operation:NSCompositeCopy fraction:1.0];
  131.     [rotated unlockFocus];
  132.     return [rotated autorelease];
  133. //save image to file
  134. - (BOOL)saveImage:(NSImage*)image                      //source image
  135.          saveType:(NSBitmapImageFileType)storageType   //save type "NSJPEGFileType"
  136.          properties:(NSDictionary *)properties         //properties "NSImageCompressionFactor = (NSNumber)0.8"
  137.          ToTarget:(NSString *) targePath               //save path
  138.     NSData *tempdata;
  139.     NSBitmapImageRep *srcImageRep;
  140. BOOL reflag = NO;
  141.     [image lockFocus];
  142.     srcImageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
  143.     tempdata = [srcImageRep representationUsingType:storageType properties:properties];
  144.     reflag = [tempdata writeToFile:targePath atomically:YES];
  145.     [image unlockFocus];
  146.     return reflag;
  147. // ---------------------------------------------------------------------------------------------------------------------
  148. - (CGImageRef)thumbnailForFile: (NSString*)name
  149.                         atPath: (NSString*)filePath
  150. // use ImageIO to get a thumbnail for a file at a given path
  151.     CGImageSourceRef    isr = NULL;
  152.     NSString *          path = [filePath stringByExpandingTildeInPath];
  153.     CGImageRef          image = NULL;
  154.   //  path = [path stringByAppendingPathComponent: name];
  155. // create the CGImageSourceRef
  156.     isr = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath: path], NULL);
  157.     if (isr)
  158. // create a thumbnail:
  159. // - specify max pixel size
  160. // - create the thumbnail with honoring the EXIF orientation flag (correct transform)
  161. // - always create the thumbnail from the full image (ignore the thumbnail that may be embedded in the image -
  162. //                                                  reason: our MAX_ICON_SIZE is larger than existing thumbnail)
  163.         image = CGImageSourceCreateThumbnailAtIndex (isr, (CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
  164.             [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] );
  165.         CFRelease(isr);
  166.     return image;
  167. }
  168. + (NSImage*) imageFromCGImageRef:(CGImageRef)image
  169.     NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0);
  170.     CGContextRef imageContext = nil;
  171.     NSImage* newImage = nil;
  172. // Get the image dimensions.
  173.     imageRect.size.height = CGImageGetHeight(image);
  174.     imageRect.size.width = CGImageGetWidth(image);
  175. // Create a new image to receive the Quartz image data.
  176.     newImage = [[[NSImage alloc] initWithSize:imageRect.size] autorelease];
  177.     [newImage lockFocus];
  178. // Get the Quartz context and draw.
  179.     imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
  180.     CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
  181.     [newImage unlockFocus];
  182.     return newImage;
  183. - (CGImageRef)nsImageToCGImageRef//:(NSImage*)image;
  184.     NSData * imageData = [self TIFFRepresentation];
  185.     CGImageRef imageRef;
  186.     if(imageData)
  187.         CGImageSourceRef imageSource =
  188.          CGImageSourceCreateWithData(
  189.                             (CFDataRef)imageData,  NULL);
  190.         imageRef = CGImageSourceCreateImageAtIndex(
  191.                                imageSource,255); color: inherit; ">     return imageRef;
  192. BOOL)setSmoothingEffect
  193.     NSBitmapImageRep *rep = [[self representations] objectAtIndex: 0];
  194.     NSSize size = NSMakeSize ([rep pixelsWide], [rep pixelsHigh]);
  195.     if(size.width >0 && size.height>0)
  196.         [self setSize: size];
  197.         return YES;
  198.     return NO;
  199.  // Generates a 256 by 256 pixel image with a complicated gradient in it.
  200. + (NSImage *) prettyGradientImage:(NSSize)gradientSize
  201.     NSImage *newImage = [[self alloc] initWithSize:gradientSize];  // In this case, the pixel dimensions match the image size.
  202. int pixelsWide = gradientSize.width;
  203. int pixelsHigh = gradientSize.height;    
  204.     NSBitmapImageRep *bitmapRep = 
  205.         [[NSBitmapImageRep alloc] 
  206.         initWithBitmapDataPlanes: nil  // Nil pointer makes the kit allocate the pixel buffer for us.
  207.         pixelsWide: pixelsWide  // The compiler will convert these to integers, but I just wanted to  make it quite explicit
  208.         pixelsHigh: pixelsHigh         bitsPerSample: 8
  209.         samplesPerPixel: 4  // Four samples, that is: RGBA
  210.         hasAlpha: YES
  211.         isPlanar: NO  // The math can be simpler with planar images, but performance suffers..
  212.         colorSpaceName: NSCalibratedRGBColorSpace  // A calibrated color space gets us ColorSync for free.
  213.         bytesPerRow: 0     // Passing zero means "you figure it out."
  214.         bitsPerPixel: 32];  // This must agree with bitsPerSample and samplesPerPixel.
  215.   
  216. char *imageBytes = [bitmapRep bitmapData];  // -bitmapData returns a void*, not an NSData object ;-)
  217. int row = pixelsHigh;
  218.     while(row--)
  219.         int col = pixelsWide;
  220.         while(col--) 
  221.         {
  222.             int 
  223.             pixelIndex = 4 * (row * pixelsWide + col);
  224.             imageBytes[pixelIndex + red] = rint(fmod(distance(NSMakePoint(col/1.5,(255-row)/1.5)),255.0));  //red
  225.             imageBytes[pixelIndex + green] = rint(fmod(distance(NSMakePoint(col/1.5, row/1.5)),0); background-color: inherit; ">// green
  226.             imageBytes[pixelIndex + blue] = rint(fmod(distance(NSMakePoint((255-col)/1.5,0); background-color: inherit; ">// blue
  227.             imageBytes[pixelIndex + alpha] = 255;  // Not doing anything tricky with the Alpha value here...
  228.         }
  229.     [newImage addRepresentation:bitmapRep];
  230.     return [newImage autorelease];
  231. float distance(NSPoint aPoint)  // Stole this from some guy named Pythagoras..  Returns the distance of aPoint from the origin.
  232.   return sqrt(aPoint.x * aPoint.x + aPoint.y *aPoint.y);
  233. //open selecter file panel
  234. /*static NSArray* openImageFiles()
  235.     // Get a list of extensions to filter in our NSOpenPanel.
  236.     NSOpenPanel* panel = [NSOpenPanel openPanel];
  237.     [panel setCanChooseDirectories:YES];    // The user can choose a folder; images in the folder are added recursively.
  238.     [panel setCanChooseFiles:YES];
  239.     [panel setAllowsMultipleSelection:YES];
  240.     if ([panel runModalForTypes:[NSImage imageUnfilteredFileTypes]] == NSOKButton)
  241.         return [panel filenames];
  242.     return nil;
  243. }*/

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

相关推荐