In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "the methods of iOS image compression, filter, clipping and rendering". In the daily operation, I believe many people have doubts about the methods of iOS image compression, filter, clipping and rendering. I have consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "iOS image compression, filter, clipping and rendering methods". Next, please follow the editor to study!
Main contents:
1. Introduction of basic knowledge of pictures.
2. Picture compression
A brief review of getting a picture from an album for direct format conversion compression: png, jpg, Context redraw
3. Picture processing
Modify picture cut clip render render screenshot based on picture pixel
The introduction of the basic knowledge of pictures
An image is a collection of pixels, each of which is independent and has its own color. Images are generally stored as an array, which can be said to be a two-dimensional array. When millions of pixels come together, they form an image. There are many ways to represent graphics in YUV,RGBA, the simplest of which is 32-bit RGBA mode. Stores the value of a color in 32 bits (or 4 bytes) and stores a color channel (RGBA) per byte.
Second, picture compression
2.1. Briefly review getting a picture from an album
When it comes to pictures of the system, photo albums and cameras are inseparable. In order to enable the real machine to successfully call the photo album / photo function when using, we need to set two key:Privacy-Camera Usage Description and Privacy-Photo Library Usage Description in the info.plist class. It is better to add them according to the crash during the test.
Key of camera and photo album
, hang two agents:
, define two button, the tag value of the album 101, camera 102, call UIImagePickerController
# pragma mark Select album-(void) selectImage: (UIButton *) sender {NSInteger tag = sender.tag-100; NSUInteger sourceType = 0; if (tag = = 1) {/ / album / / 1. Judge whether the photo gallery can be opened (direct return is not supported) if (! [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return; sourceType = UIImagePickerControllerSourceTypePhotoLibrary;} else if (tag = = 2) {/ / photo / / 2. Determine whether to support camera (direct return) if (! [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return; sourceType = UIImagePickerControllerSourceTypeCamera;} UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init]; / / set proxy imagePickerController.delegate = self; / / imagePickerController.allowsEditing = YES; imagePickerController.sourceType = sourceType; [self presentViewController:imagePickerController animated:YES completion:nil];}
, the implementation of the UIImagePickerController proxy method (remove the edited pictures for the time being)
# pragma mark-UIImagePicker delegate- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {NSString * mediaType= [info objectForKey:UIImagePickerControllerMediaType]; / / the acquired image if ([mediaType isEqualToString:@ "public.image"]) {UIImage * image; / / determine whether the image is allowed to be modified / / if ([picker allowsEditing]) {/ / get the edited image / / image = [info objectForKey:UIImagePickerControllerEditedImage] / / else {/ / metadata parameter image = [info objectForKey:UIImagePickerControllerOriginalImage]; / /} / / compress the image (processing) see below} [self dismissViewControllerAnimated:YES completion:NULL];} / / when the user cancels the selection, call this method-(void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {NSLog (@ "cancel the use of the album--% s", _ _ func__) [self dismissViewControllerAnimated:YES completion:nil];}
, calculate the size of NSData
# pragma mark calculates the size of the NSData-(NSString*) length: (NSInteger) length {if (length > 1024) {int mb = (int) length/ (1024); int kb = (length% (1024)) / 1024; return [NSString stringWithFormat:@ "% dMb%dKB", mb, kb];} else {return [NSString stringWithFormat:@ "% ldKB", length/1024];}}
2.2. We have already got the picture above, so the compression of our team's picture will be processed below.
: png compression
/ / compress NSData * dataPNG = UIImagePNGRepresentation (image); UIImage * compressPNGImage = [UIImage imageWithData:dataPNG]; NSLog (@ "% @", [self length:dataPNG.length])
Tip:
This compression method will cause a surge in memory and the file attribute format will not be compressed, but the image content (pixels) will be compressed.
: jpg compression
/ * * first parameter: UIIMage object second parameter: image quality (compression factor) 0.1 * / NSData * dataJPG = UIImageJPEGRepresentation (image, 0.1); UIImage * compressJPGImage = [UIImage imageWithData:dataJPG]; NSLog (@ "% @", [self length:dataJPG.length])
Tip:
1. If you compress a picture through JPEG, it will not be true after compression.
two。 Apple officially does not recommend us to use JPG images because decompressing real JPG images consumes a lot of performance.
3. Although this compression method can be used to set the picture quality, there will also be a surge in memory.
Custom size compression compresses pictures through context
UIImage * compressImg = [self compressOriginalImage:image withImageSize:CGSizeMake (200,200)]; NSLog (@ "% @", NSStringFromCGSize (compressImg.size)); / / compress the image-(UIImage *) compressOriginalImage: (UIImage *) originalImage withImageSize: (CGSize) size {/ / enable the picture context UIGraphicsBeginImageContext (size); / / render the picture to the picture context [originalImage drawInRect:CGRectMake (0,0, size.width, size.height)]; / / get the picture UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext () / / close the picture context UIGraphicsEndImageContext (); return newImage;}
Tip: this method solves the surge of memory and is a good way to compress.
Note: in general, as long as the function of getting pictures from photo albums is involved, memory needs to be processed. In general, an application will take up about 20m of memory to start. When the memory soars to about 500m, the system will send a memory warning. At this time, you need to release memory, otherwise it will flicker, as long as the memory is released to about 100m, then the system will not flash our application. In other words, 20-100 memory occupied by an application is a relatively safe range of content.
3. Picture processing
3.1. Modify based on picture pixels
, filter the picture: it involves the pixel processing of the picture, which is also operated according to the context, and makes a drawing. Take out the pixels of the picture data from the picture file (RGBA), operate on the pixels, make a conversion (Bitmap (GPU)), and restore (the attributes of the picture RGBA,RGBA (width, height, color value space, width and height, how many pixels each are drawn, and how many lines are drawn).
Filter pictures
-(void) filterImage {CGImageRef imageRef = self.imageView1.image.CGImage; / / 1 byte = 8bit 17152 per line has 17152 "8 bits size_t width = CGImageGetWidth (imageRef); size_t height = CGImageGetHeight (imageRef); size_t bits = CGImageGetBitsPerComponent (imageRef); / / 8 size_t bitsPerrow = CGImageGetBytesPerRow (imageRef); / / width * bits / / color space CGColorSpaceRef colorSpace = CGImageGetColorSpace (imageRef); / / AlphaInfo: RGBA AGBR RGB: AlphaInfo information CGImageAlphaInfo alpInfo = CGImageGetAlphaInfo (imageRef) / / data for bitmap CGDataProviderRef providerRef = CGImageGetDataProvider (imageRef); CFDataRef bitmapData = CGDataProviderCopyData (providerRef); NSInteger pixLength = CFDataGetLength (bitmapData); / / Pixel byte array Byte * pixbuf = CFDataGetMutableBytePtr ((CFMutableDataRef) bitmapData); / / RGBA is a unit for (int I = 0; I < pixLength; item4) {[self eocImageFiletPixBuf:pixbuf offset:i] } / / ready to draw the picture / / bitmap generates a context and then generates the picture CGContextRef contextR = CGBitmapContextCreate (pixbuf, width, height, bits, bitsPerrow, colorSpace, alpInfo) through the context; CGImageRef filterImageRef = CGBitmapContextCreateImage (contextR); UIImage * filterImage = [UIImage imageWithCGImage:filterImageRef]; self.imageView1.image = filterImage;} / / RGBA is a unit of color irradiated black and white-(void) eocImageFiletPixBuf: (Byte*) pixBuf offset: (int) offset {int offsetR = offset; int offsetG = offset + 1 Int offsetB = offset + 2; / / int offsetA = offset + 3; int red = pixBuf [offsetR]; int gre = pixBuf [offsetG]; int blu = pixBuf [offsetB]; / / int alp = pixBuf [offsetA]; int gray = (red + gre + blu) / 3; pixBuf [offsetR] = gray; pixBuf [offsetG] = gray; pixBuf [offsetB] = gray;}
Restore the picture: there is nothing to say about this, just save the UIIMage of the filtered image and assign the value again
3.2.Photo clipping clip
Picture cut clip
, regular picture cutting (circle, rectangle, etc.)
# pragma mark clipping image (regular clipping)-(void) clipImage {CGSize size = CGSizeMake (100,100); / / Open context UIGraphicsBeginImageContext (size); / / get the current context CGContextRef context = UIGraphicsGetCurrentContext (); / / set path clipping (set a circle) CGRect rect = CGRectMake (0,0, size.width, size.height); CGContextAddEllipseInRect (context, rect); CGContextClip (context) / / draw the picture on [self.oriImage drawInRect:CGRectMake (0,0, size.width, size.height)]; UIImage * clipImage = UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext (); / / display the cut image self.imageView2.image = clipImage;}
, irregular image clipping (according to custom path clipping)
# pragma mark cut images (irregular cut images)-(void) irRegularclipImage {UIGraphicsBeginImageContext (CGSizeMake (200,200)); CGContextRef context = UIGraphicsGetCurrentContext (); / / irregular path CGMutablePathRef pathRef = CGPathCreateMutable (); CGPoint lines [] = {CGPointMake (50L0), CGPointMake (100L0), CGPointMake (150J 80), CGPointMake (0jue 80), CGPointMake (50J 0)}; CGPathAddLines (pathRef, NULL, lines, 5); CGContextAddPath (context, pathRef); CGContextClip (context); [self.oriImage drawInRect:CGRectMake (0,200,200)] UIImage * clipImage = UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext (); / / display the cut image self.imageView3.image = clipImage;}
3.3. Picture rendering
# pragma mark renders a layer of translucent red on the picture-(void) blend {/ / the size of the original image CGSize size = CGSizeMake (self.imageView1.frame.size.width, self.imageView1.frame.size.height); UIGraphicsBeginImageContext (size); CGContextRef context = UIGraphicsGetCurrentContext (); [self.oriImage drawInRect:CGRectMake (0,0, size.width, size.height)]; / / set translucent red rendering UIColor * redColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5] CGContextSetFillColorWithColor (context, redColor.CGColor); CGContextSetBlendMode (context, kCGBlendModeNormal); CGContextFillRect (context, CGRectMake (0,0, size.width, size.height)); / / get rendered CGImageRef CGImageRef imageRef = CGBitmapContextCreateImage (context); self.imageView1.image = [UIImage imageWithCGImage:imageRef]; UIGraphicsEndImageContext ();}
3.4.Screenshot (capture all views on an object). Let's take the view of self.view as an example.
Screenshot * * (capture all views on an object). Let's take the view of self.view as an example.
, screenshot mode 1
-(UIImage *) jk_snapshotImage {UIGraphicsBeginImageContextWithOptions (self.bounds.size, YES, 0); [self.view drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES]; UIImage * result = UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext (); return result;}
, screenshot mode 1
-(UIImage *) imageFromFullView {UIGraphicsBeginImageContext (self.view.frame.size); CGContextRef context = UIGraphicsGetCurrentContext (); [self.view.layer renderInContext:context]; CGImageRef imageRef = CGBitmapContextCreateImage (context); UIImage * newImage = [UIImage imageWithCGImage:imageRef]; UIGraphicsEndImageContext (); return newImage;}
At this point, the study of "iOS image compression, filter, clipping and rendering methods" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 254
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.