Photo album photo picker github.com/banchichen/… YYImage instead of SDWebImage blog.csdn.net/zhonggaoron…

Get images from urls (asynchronously loaded)

To use SDWebImage, you simply need to provide a url and a placeholder for the download to retrieve the downloaded image in the callback

  • Use the ImageView control
#import <SDWebImage/UIImageView+WebCache.h> [imageview sd_setImageWithURL:[NSURL URLWithString:@"......"] placeholderImage:[UIImage imageNamed:@"placeholder"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {imageview.image = image; NSLog(@" image load complete ");}]; [imageView sd_setImageWithURL:[NSURL URLWithString:@"....."]];Copy the code
  • Button control use
#import <SDWebImage/UIButton+WebCache.h> [self.headBtn sd_setImageWithURL:[NSURL URLWithString:headImgUrl] ForState: UIControlStateNormal placeholderImage: [UIImage imageNamed: @ "login 2"]].Copy the code

Get images from URL (synchronous loading)

NSString *imgurl = @"....." ; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgurl]]; UIImage *img3 = [UIImage imageWithData:data];Copy the code

Loading local images

NSString *path = [[NSBundle mainBundle] pathForResource:@"xx" ofType:@"png"]; UIImage *image = [UIImage imageWithContentsOfFile:path]; Or NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType: "PNG"]; NSData *image = [NSData dataWithContentsOfFile:filePath]; UIImage *image = [UIImage imageWithData:image];Copy the code

The difference between loading methods

ImageWithContentsOfFile: Only images are loaded, image data is not cached. Suitable for loading large images and less used scenarios to reduce memory consumption. ImageNamed: Finds and returns an image object in the system cache if it exists. If no corresponding image is found in the cache, this method loads the object from the specified document and then caches and returns the object. Suitable for frequent use of images.

Image NSData conversion

NSData *imageData = [NSData dataWithContentsOfFile: imagePath]; UIImage *image = [UIImage imageWithData: imageData]; NSData *imageData = UIImagePNGRepresentation(image);Copy the code

screenshots

-(void)cutScreenPic{// Enable context CGSize imageSize = self.view.bounds.size; UIGraphicsBeginImageContextWithOptions (imageSize, NO, 0.0); / / will be a View of all content rendering to the graphics context CGContextRef context = UIGraphicsGetCurrentContext (); [self.view.layer renderInContext:context]; / / get the picture UIImage * image = UIGraphicsGetImageFromCurrentImageContext (); / / save [UIImagePNGRepresentation (image) writeToFile: @ "/ Users/CC/Desktop/imageName PNG" atomically: YES]; }Copy the code

Change image rendering (set Rander)

    img = [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];  
Copy the code

The compressed image

/* compress image to specified pixel */ - (UIImage *)rescaleImageToPX:(CGFloat)toPX{CGSize size = self.size; if(size.width <= toPX && size.height <= toPX) return self; CGFloat scale = size.width/size.height; CGFloat scale = size.width/size.height; If (size.width > size.height){size.width = toPX; size.height = size.width / scale; } else{ size.height = toPX; size.width = size.height * scale; } return [self rescaleImageToSize:size]; } /* compress image to specified size */ - (UIImage *)rescaleImageToSize:(CGSize)size {CGRect rect = (CGRect){CGPointZero, size}; UIGraphicsBeginImageContext(rect.size); [self drawInRect:rect]; UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resImage; }Copy the code
+ (UIImage *)compressImage:(UIImage *)imgSrc withSize:(CGSize)size  {  

    UIGraphicsBeginImageContext(size);  
    CGRect rect = {{0,0}, size};  
    [imgSrc drawInRect:rect];  
    UIImage *compressedImg = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext();  

    return compressedImg;  
}
Copy the code

Multiple images

www.jianshu.com/p/6181f32bb…

Chat bubble sharp corner pictures

www.jianshu.com/p/c6c645394…

Compare two pictures to see if they are equal

- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2
{
    NSData *data1 = UIImagePNGRepresentation(image1);
    NSData *data2 = UIImagePNGRepresentation(image2);

    return [data1 isEqual:data2];
}
Copy the code

Judge the type of picture

// Encapsulate tool methods. - (NSString *)contentTypeForImageData:(NSData *) Data {uint8_t c; [data getBytes:&c length:1]; switch (c) { case 0xFF: return @"jpeg"; case 0x89: return @"png"; case 0x47: return @"gif"; case 0x49: case 0x4D: return @"tiff"; case 0x52: if ([data length] < 12) { return nil; } NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { return @"webp"; } return nil; } return nil; } // call // assume this is a network-fetched URL NSString *path = @"http://pic.rpgsky.net/images/2016/07/26/3508cde5f0d29243c7d2ecbd6b9a30f1.png"; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:path]]; / / call get photo extension nsstrings * string = [self contentTypeForImageData: data]; PNG NSLog(@"%@",string);Copy the code

Draw text on a picture

// custom tool method - (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize {// canvas size CGSize size=CGSizeMake(self.size.width,self.size.height); / / create a context based on bitmap UIGraphicsBeginImageContextWithOptions (size, NO, 0.0); / / opaque: NO scale: 0.0 [self drawAtPoint: CGPointMake (0.0, 0.0)]. NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping; paragraphStyle.alignment=NSTextAlignmentCenter; Centered text / / / / computing the size of the text, the text centered on the canvas CGSize sizeText = [title boundingRectWithSize: self. The size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size; CGFloat width = self.size.width; CGFloat height = self.size.height; CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height); // draw text [title drawInRect:rect withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}]; / / return draw new graphics UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext(); return newImage; }Copy the code

Drawing pictures

Example: QQ session window, bubble background image stretching

ResizeWithImage :(UIImage *)image{CGFloat top = image.sie.height /2.0; CGFloat left = image. The size. Width / 2.0; CGFloat bottom = image, the size height / 2.0; CGFloat right = image. The size. Width / 2.0; return [image resizableImageWithCapInsets:UIEdgeInsetsMake(top, left, bottom, right)resizingMode:UIImageResizingModeStretch]; } - (UIImage *) resizableImageWithCapInsets: UIEdgeInsets capInsets resizingMode (UIImageResizingMode) resizingMode; // This method returns the stretched image. The second parameter is resizingMode image stretching modes: UIImageResizingModeTile tile, UIImageResizingModeStretch, stretchingCopy the code

Obtain grayscale map

+ (UIImage*)covertToGrayImageFromImage:(UIImage*)sourceImage { int width = sourceImage.size.width; int height = sourceImage.size.height; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); CGContextRef context = CGBitmapContextCreate (nil, width, height, 8, 0, the colorSpace, kCGImageAlphaNone); CGColorSpaceRelease(colorSpace); if (context == NULL) { return nil; } CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage); CGImageRef contextRef = CGBitmapContextCreateImage(context); UIImage *grayImage = [UIImage imageWithCGImage:contextRef]; CGContextRelease(context); CGImageRelease(contextRef); return grayImage; }Copy the code

The View generates the image

- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size {// The second parameter indicates whether it is opaque. Translucency effect must pass NO, otherwise pass YES. The third parameter is the screen density [UIScreen mainScreen].scale. UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }Copy the code

Gets the RGB of a point in the picture

- (UIColor *)colorAtPixel:(CGPoint)point { // Cancel if point is outside image coordinates if (! CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.sie.width, self.sie.height), point)) {return nil; } NSInteger pointX = trunc(point.x); NSInteger pointY = trunc(point.y); CGImageRef cgImage = self.CGImage; NSUInteger width = self.size.width; NSUInteger height = self.size.height; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); int bytesPerPixel = 4; int bytesPerRow = bytesPerPixel * 1; NSUInteger bitsPerComponent = 8; unsigned char pixelData[4] = { 0, 0, 0, 0 }; CGContextRef context = CGBitmapContextCreate(pixelData, 1, 1, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); CGColorSpaceRelease(colorSpace); CGContextSetBlendMode(context, kCGBlendModeCopy); // Draw the pixel we are interested in onto the bitmap context CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height); CGContextDrawImage(Context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage); CGContextDrawImage(Context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height); CGContextRelease(context); Floats [0.0..1.0] CGFloat Red = (CGFloat)pixelData[0] / 255.0f; // Convert color values [0..255] to floats [0.0..1.0] CGFloat Red = (CGFloat)pixelData[0] / 255.0f; CGFloat green = (CGFloat)pixelData[1] / 255.0f; CGFloat blue = (CGFloat)pixelData[2] / 255.0f; CGFloat alpha = (CGFloat)pixelData[3] / 255.0f; return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; }Copy the code

Generates solid color images

- (UIImage *)imageWithColor:(UIColor *)color {CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); / / open the bitmap context UIGraphicsBeginImageContext (the rect. Size); / / get the bitmap context CGContextRef context = UIGraphicsGetCurrentContext (); / / use the color demo CGContextSetFillColorWithColor populate the context (context, [color CGColor]); CGContextFillRect(context, rect); / / to get pictures from the context of UIImage * theImage = UIGraphicsGetImageFromCurrentImageContext (); / / end context UIGraphicsEndImageContext (); return theImage; }Copy the code

Frosted glass effect

Read the picture based on the file name in the bundle

+ (UIImage *)imageWithFileName:(NSString *)name { NSString *extension = @"png"; NSArray *components = [name componentsSeparatedByString:@"."]; if ([components count] >= 2) { NSUInteger lastIndex = components.count - 1; extension = [components objectAtIndex:lastIndex]; name = [name substringToIndex:(name.length-(extension.length+1))]; } // If the screen is Retina and the corresponding image exists, return the Retina image, If ([UIScreen mainScreen].scale == 2.0) {name = [name stringByAppendingString:@"@2x"]; NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension]; if (path ! = nil) { return [UIImage imageWithContentsOfFile:path]; }} if ([UIScreen mainScreen].scale == 3.0) {name = [name stringByAppendingString:@"@3x"]; NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension]; if (path ! = nil) { return [UIImage imageWithContentsOfFile:path]; } } NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension]; if (path) { return [UIImage imageWithContentsOfFile:path]; } return nil; }Copy the code

Save the image locally

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
Copy the code

Save the picture to your local album

-(void)saveImage:(UIImage *)img{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL); }); } - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{ if(error ! = NULL){SVProgressHUD showNOmessage:@" save failed "]; }else{SVProgressHUD showYESmessage:@" save successfully "]; }}Copy the code

Save to new album

Blog.csdn.net/sdefzhpk/ar…

Image merging

+ (UIImage *)imageCombineImage:(UIImage *)useImage maskImage:(UIImage *)maskImage { UIGraphicsBeginImageContextWithOptions (useImage. Size, NO, 0.0); [useImage drawInRect:CGRectMake(0, 0, useImage.size.width, useImage.size.height)]; [maskImage drawInRect:CGRectMake(50, 50, 50, 50)]; // If you want to display multiple positions, //[maskImage drawInRect:CGRectMake(0, useimage.sie.height /2, useimage.sie.width, useImage.size.height/2)]; UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resultImage; }Copy the code

UIImage and Base64 images are converted to each other

/ / - (NSString *)encodeToBase64String:(UIImage *)image {return [UIImagePNGRepresentation(image)) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; } - (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData { NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters]; return [UIImage imageWithData:data]; } /* Method 2 */ - (BOOL) imageHasAlpha: (UIImage *) image {CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.cgImage); return (alpha == kCGImageAlphaFirst || alpha == kCGImageAlphaLast || alpha == kCGImageAlphaPremultipliedFirst || alpha == kCGImageAlphaPremultipliedLast); } - (NSString *) image2DataURL: (UIImage *) image { NSData *imageData = nil; NSString *mimeType = nil; if ([self imageHasAlpha: image]) { imageData = UIImagePNGRepresentation(image); mimeType = @"image/png"; } else {imageData = UIImageJPEGRepresentation (image, 1.0 f); mimeType = @"image/jpeg"; } return [NSString stringWithFormat:@"data:%@;base64,%@", mimeType, [imageData base64EncodedStringWithOptions: 0]]; } - (UIImage *) dataURL2Image: (NSString *) imgSrc { NSURL *url = [NSURL URLWithString: imgSrc]; NSData *data = [NSData dataWithContentsOfURL: url]; UIImage *image = [UIImage imageWithData: data]; return image; }Copy the code

The image processing

Github.com/lisongrc/UI…

Upload multiple pictures

www.jianshu.com/p/f147942a5…