Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a subimage from a UIImage

Tags:

iphone

I want to grab a subimage from a UIImage. I've looked around for a similar question, to no avail.

I know the range of pixels I want to grab - how can I return this subimage, from an existing image?

like image 569
Don Wilson Avatar asked Dec 18 '10 00:12

Don Wilson


People also ask

What is the difference between UIImage and UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

How do I copy UIImage?

Deep copying UIImage *newImage = [UIImage imageWithData:UIImagePNGRepresentation(oldImage)]; This will copy the data but will require setting the orientation property before handing it to something like UIImageView for proper display. Another way to deep copy would be to draw into the context and grab the result.

How do you declare UIImage in Objective C?

For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]]; My UIImage object is declared in .


Video Answer


2 Answers

This should help: http://iphonedevelopment.blogspot.com/2010/11/drawing-part-of-uiimage.html

This code snippet is creating a category of UIImage but the code should be easily modified to work without it being a category.

A shorter way of doing the same thing is the following:

CGRect fromRect = CGRectMake(0, 0, 320, 480); // or whatever rectangle

CGImageRef drawImage = CGImageCreateWithImageInRect(image.CGImage, fromRect);
UIImage *newImage = [UIImage imageWithCGImage:drawImage];
CGImageRelease(drawImage);

Hope this helps!

like image 118
donkim Avatar answered Oct 27 '22 01:10

donkim


Updated @donkim answer for swift 3:

    let fromRect=CGRect(x:0,y:0,width:320,height:480)
    let drawImage = image.cgImage!.cropping(to: fromRect)
    let bimage = UIImage(cgImage: drawImage!)
like image 21
T. Cervenka Avatar answered Oct 27 '22 01:10

T. Cervenka