Image processing code snippets to process code snippets

Source: Internet
Author: User

Image processing code snippets to process code snippets
1. image Scaling: code-(UIImage *) resizeImage :( UIImage *) image toWidth :( NSInteger) width height :( NSInteger) height {// Create a graphics context with the target size // On iOS 4 and later, use uigraphicsbeginimagecontextwittions to take the scale into consideration // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext CGSize size = CGSizeMake (width, height); if (NULL! = Optional) uigraphicsbeginimagecontextwitexceptions (size, NO, 0); else UIGraphicsBeginImageContext (size); CGContextRef context = UIGraphicsGetCurrentContext (); // Flip the context because UIKit coordinate system is upside down to Quartz coordinate system CGContextTranslateCTM (context, 0.0, height); CGContextScaleCTM (context, 1.0,-1.0 ); // Draw the original image to Context CGContextSetBlendMode (context, kCGBlendModeCopy); CGContextDrawImage (context, CGRectMake (0.0, 0.0, width, height), image. CGImage); // Retrieve the UIImage from the current context UIImage * imageOut = UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext (); return imageOut;} 2. UIView rotation: code-(void) rotateView :( UIView *) view toAngle :( float) angle {[UIView beginAnimations: nil co Ntext: nil]; [view setTransform: CGAffineTransformMakeRotation (angle)]; [UIView commitAnimations];} 3. color processing function: Code # pragma mark Color convert-(UIColor *) str2Color :( NSString *) str {SEL blackSel = NSSelectorFromString (str); // NSSelectorFromString (@ "blackColor "); UIColor * tColor = nil; if ([UIColor respondsToSelector: blackSel]) tColor = [UIColor performSelector: blackSel]; return tColor;}-(UIColor *) HexStr2Color :( NSString *) hexStr {NSString * cString = [hexStr stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet] uppercaseString]; // String shoshould be 6 or 8 characters if ([cString length] <6) return [UIColor blackColor]; // strip 0X if it appears if ([cString hasPrefix: @ "0X"]) cString = [cString substringFromIndex: 2]; if ([cString length]! = 6) return [UIColor blackColor]; // Separate into r, g, B substrings nsange range; range. location = 0; range. length = 2; NSString * rString = [cString substringWithRange: range]; range. location = 2; NSString * gString = [cString substringWithRange: range]; range. location = 4; NSString * bString = [cString substringWithRange: range]; // Scan values unsigned int r, g, B; [[ns1_scannerwithstring: rSt Ring] scanHexInt: & r]; [[ns1_scannerwithstring: gString] scanHexInt: & g]; [ns1_scannerwithstring: bString] scanHexInt: & B]; return [UIColor colorWithRed :( (float) r/255.0f) green :( (float) g/255.0f) blue :( (float) B/255.0f) alpha: 1.0f];} -(NSString *) color2str :( UIColor *) color {CGColorRef c = color. CGColor; const CGFloat * components = CGColorGetComponents (c); size_t numberOfComponent S = CGColorGetNumberOfComponents (c); NSMutableString * s = [[NSMutableString alloc] init] autorelease]; [s appendString: @ "{"]; for (size_t I = 0; I <numberOfComponents; ++ I) {if (I> 0) {[s appendString: @ ","];} [s appendString: [NSString stringWithFormat: @ "% d", (int) (components [I] * 255)];} [s appendString: @ "}"]; return s ;}- (NSString *) color2str1 :( UIColor *) color {const CGFloat * components = CGColorGetComponents (color. CGColor); NSString * colorAsString = [NSString stringWithFormat: @ "% 1f, % 1f, % 1f, % 1f", components [0] * 255, components [1] * 255, components [2] * 255, components [3];} 4. the angle corresponding to the intermediate point of the Three-Point coordinate, and determine whether the code is clockwise-(BOOL) chkClockWise :( CGPoint) a B :( CGPoint) B C :( CGPoint) c {double ax =. x-B. x; double ay =-. y + B. y; double cx = c. x-B. x; double cy =-c. y + B. y; NSLog (@ "result: % d", (cy * ax) <= (Y * cx); NSLog (@ "(x1, y1) = (% 1f, % 1f)", ax, ay); NSLog (@ "(x2, y2) = (% 1f, % 1f) \ r \ n ", cx, cy); return (cy * ax) <= (ay * cx ));} 5. after the coordinates are rotated, the new coordinates are obtained: code-(CGPoint) getNewPoint: (CGPoint) old rotate :( double) rotate {// The actual coordinates are converted to the origin coordinate old. x = (old. x-center.x); old. y = (center. y-old.y); // calculate the new coordinate after selection double x = old. x * cos (rotate)-old. y * sin (rotate); double y = old. y * cos (rotate) + old. x * sin (rotate); // The origin coordinate is converted to the actual coordinate x = center. x + x; Y = center. y-y; return CGPointMake (x, y);} 6. capture the color of any point in UIView: code-(UIColor *) getPixelColorAtLocation :( CGPoint) point {UIGraphicsBeginImageContext (self. bounds. size); [self. layer renderInContext: UIGraphicsGetCurrentContext ()]; UIImage * viewImage = UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext (); CGImageRef inImage = viewImage. CGImage; UIColor * color = nil; // Create off Screen bitmap context to draw the image. format ARGB is 4 bytes for each pixel: Alpa, Red, Green, Blue CGContextRef cgctx = [self createARGBBitmapContextFromImage: inImage]; if (cgctx = NULL) {return nil; /* error */} size_t w = CGImageGetWidth (inImage); size_t h = CGImageGetHeight (inImage); CGRect rect = {0, 0}, {w, h }}; // Draw the image to the bitmap context. once we draw, the memory // al Located for the context for rendering will then contain the // raw image data in the specified color space. CGContextDrawImage (cgctx, rect, inImage); // Now we can get a pointer to the image data associated with the bitmap // context. unsigned char * data = CGBitmapContextGetData (cgctx); if (data! = NULL) {// offset locates the pixel in the data from x, y. // 4 for 4 bytes of data per pixel, w is width of one row of data. int offset = 4 * (w * round (point. y) + round (point. x); int alpha = data [offset]; int red = data [offset + 1]; int green = data [offset + 2]; int blue = data [offset + 3]; NSLog (@ "offset: % I colors: rgb a % I", offset, red, green, blue, alpha); color = [UIColor colorWithRed :( red/255.0f) Green :( green/255.0f) blue :( blue/255.0f) alpha :( alpha/255.0f)];} // When finished, release the context CGContextRelease (cgctx ); // Free image data memory for the context if (data) {free (data);} return color;}-(CGContextRef) createARGBBitmapContextFromImage :( CGImageRef) inImage {CGContextRef context = NULL; CGColorSpaceRef colorSpace; void * bitmapData; int bitmapByteCount; int bitmapBytesPe RRow; // Get image width, height. we'll use the entire image. size_t pixelsWide = CGImageGetWidth (inImage); size_t pixelsHigh = CGImageGetHeight (inImage); // Declare the number of bytes per row. each pixel in the bitmap in this // example is represented by 4 bytes; 8 bits each of red, green, blue, and // alpha. bitmapBytesPerRow = (pixelsWide * 4); bitmapByteCount = (bitmapBytesPerRow * pixelsHigh ); // Use the generic RGB color space. colorSpace = CGColorSpaceCreateDeviceRGB (); if (colorSpace = NULL) {fprintf (stderr, "Error allocating color space \ n"); return NULL;} // Allocate memory for image data. this is the destination in memory // where any drawing to the bitmap context will be rendered. bitmapData = malloc (bitmapByteCount); if (bitmapData = NULL) {fprintf (stderr, "Memory not Allocated! "); CGColorSpaceRelease (colorSpace); return NULL;} // Create the bitmap context. we want pre-multiplied ARGB, 8-bits // per component. regardless of what the source image format is // (CMYK, Grayscale, and so on) it will be converted over to the format // specified here by CGBitmapContextCreate. context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8, // bits per component bitmapB YtesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst); if (context = NULL) {free (bitmapData); fprintf (stderr, "Context not created! ");} // Make sure and release colorspace before returning CGColorSpaceRelease (colorSpace); return context;} 7. one method to implement screenshot capture in the iphone program: // import the header file # import <QuartzCore/QuartzCore. h> // set the entire self. create an image imageUIGraphicsBeginImageContext (self. view. bounds. size); [self. view. layer renderInContext: UIGraphicsGetCurrentContext ()]; UIImage * image = encrypt (); UIGraphicsEndImageContext (); // Save the image to the image UIImageWriteToSavedPhotosAlbum (image, self, nil, nil); 8. draw a dot image:-(UIImage *) createImage {CGSize size = [[UIScreen mainScreen] bounds]. size; CGRect rect = CGRectMake (size. width/2, size. height/2, 5, 5); UIGraphicsBeginImageContext (size); CGContextRef context = UIGraphicsGetCurrentContext (); unsigned int red, green, blue; // Fill color. CGContextSetRGBFillColor (context, 0, 0.7, 0.7, 1.0); // Your drawing code. CGContextFillEllipseInRect (context, rect); // Get the image and return. UIImage * image = UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext (); return image ;}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.