0

I am working on Camera Application user are taking a picture its fine,but i want to crop anywhere in that image and send it to server. How can I do this?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
pinku
  • 87
  • 1
  • 7

2 Answers2

3

Check out this link for details:

http://www.hive05.com/2008/11/crop-an-image-using-the-iphone-sdk/

Basic code:

- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
   //create a context to do our clipping in
   UIGraphicsBeginImageContext(rect.size);
   CGContextRef currentContext = UIGraphicsGetCurrentContext();

   //create a rect with the size we want to crop the image to
   //the X and Y here are zero so we start at the beginning of our
   //newly created context
   CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
   CGContextClipToRect( currentContext, clippedRect);

   //create a rect equivalent to the full size of the image
   //offset the rect by the X and Y we want to start the crop
   //from in order to cut off anything before them
   CGRect drawRect = CGRectMake(rect.origin.x * -1,
                                rect.origin.y * -1,
                                imageToCrop.size.width,
                                imageToCrop.size.height);

   //draw the image to our clipped context using our offset rect
   CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);

   //pull the image from our cropped context
   UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();

   //pop the context to get back to the default
   UIGraphicsEndImageContext();

   //Note: this is autoreleased
   return cropped;
}
Bushra Shahid
  • 3,579
  • 1
  • 27
  • 37
2

I think i can provide a better solution to that large amount of code.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // do something......
    UIImage *croppedImage = [self imageByCropping:[UIImage imageNamed:@"SomeImage.png"] toRect:CGRectMake(10, 10, 100, 100)];
}
- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
   CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
   UIImage *cropped = [UIImage imageWithCGImage:imageRef];
   return cropped;
}
Robin
  • 10,011
  • 5
  • 49
  • 75
  • Thanks @robin for answering me. Please let me know where i put his code. – pinku Aug 10 '11 at 06:43
  • ok i want to call it on viewdidload method how to call this. i am writing [self imageToCrop]; it gives error. please let me know how to write. – pinku Aug 10 '11 at 06:55
  • my image size is 150 * 120 (width * height) – pinku Aug 10 '11 at 07:44
  • are you displaying this image somewhere in your view. Also can you tell me how are you planning on sending this image. – Robin Aug 10 '11 at 07:47