ios - Can crop photo vertical but not horizontal - ios

I have a UIScrollView with a UIImageView inside of it. For this part of my app, the user can select photos from their camera roll and scale and crop them.
I have successfully made the user be able select different photos, then zoom in and out & pan around the image. Also, the user can zoom out to make the image centre vertically or horizontally depending on if the image is portrait or landscape.
The problem is, I try to then crop the photo from the visible rect in the scroll view to a new image, however its only working for portrait photos.
Here is an example of it working then not working:
Here is a portrait image that is zoomed out to fit the screen:
Next, I zoom in the image so there is no black space.
Finally, I crop the photo and you can see it crops perfectly in the top left hand corner.
However, for some reason when I try to do this with a landscape image the cropping messes up?! Here is an example of it not working.
Here is a zoomed out landscape image.
Next, I zoom in so there is no black space left. Notice how I zoomed in specifically so there is no physical boarder of the white board visible in the photo.
Now, I crop the photo just like before and it doesn't crop it properly. Notice how in the top left hand corner the image is different from before. It appears to have been zoomed out and you can see more of the bottom of the white board.
I need to figure out why this is happening and how to fix it.
Here is the exact code I use to crop the photo from the UIScrollView.
//Get the scale
float scale = 1.0f/_libraryScrollView.zoomScale;
//Create a new rect
CGRect visibleRect;
visibleRect.origin.x = _libraryScrollView.contentOffset.x * scale;
visibleRect.origin.y = _libraryScrollView.contentOffset.y * scale;
visibleRect.size.width = _libraryScrollView.bounds.size.width * scale;
visibleRect.size.height = _libraryScrollView.bounds.size.height * scale;
//Get the source image
UIImage *src = libraryPreviewImageView.image;
//Create the new cropped image with the rect
CGImageRef cr = CGImageCreateWithImageInRect(src.CGImage, visibleRect);
UIImage *finalImage = [[UIImage alloc]initWithCGImage:cr];
//Set the new image to the preview image view
self.imagePreviewView.image = finalImage;
This code works for portrait images but doesn't work for landscape images as shown above in the examples. Is this error to do with my cropping code or is it to do with something else?
Any help would be appreciated.

In the end, I had no idea what was the problem but trying to use maths to crop an image from a scroll view is extremely difficult!
I found a really easy way and that is to take a screen shot of the visible content in the scroll view, its as easy as this:
UIGraphicsBeginImageContextWithOptions(_libraryScrollView.bounds.size, YES, [UIScreen mainScreen].scale);
CGPoint offset = _libraryScrollView.contentOffset;
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -offset.x, -offset.y);
[_libraryScrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Set the new image to the preview image view
self.imagePreviewView.image = finalImage;
I really hope this answer can help other people out too!

Related

Draw the zoomed & panned portion of a UIScrollview as a new UIImage

I would like to draw a thumbnail of a UIScrollview.
This scrollview has an image in. However the user can zoom and pan the image.
When the user has panned and zoomed to where he wants the picture, I want to create a thumbnail of what they set up. Basically, I want to create a brand new uiimage that is sized at say 100x100, but uses the exact image data that the scrollview is currently showing.
I tried this, but the more I zoom in, the more distorted the images became.
//returns a smaller UIImage
func generateThumbnailOfSize(size:CGSize)->UIImage
{
UIGraphicsBeginImageContext(_scrollView.bounds.size)
_scrollView.layer.renderInContext(UIGraphicsGetCurrentContext())
var fullsizeCroppedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width, size.height), fullsizeCroppedImage.CGImage)
var sizeAdjustedCroppedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()//gets the image as it looks in the scrollview
UIGraphicsEndImageContext()
return sizeAdjustedCroppedImage
}
Suggestions?:)
Swift & Objc code welcome!
You may want to have a look at this:
Crop UIImage in UIScrollView like in "Move And Scale"
In case anyone is interested in more sophisticated solution:
https://github.com/barrettj/BJImageCropper

need a very tiny (rectangular in shape) overlay over UIImagePickerController, and then crop the image accordingly - UPDATED

In my application, i need the user to take a snap of only a 10 letter word (using overlay, which should be right in the centre of the screen of the UIImagePicker), and then in need to show him that image (only the part of the image covered by that rectangle). So, I need to crop that image according to the overlay.
Here, i have taken a picture using UIImagePickerControl. Now, i want to see the dimensions of the image that i have taken..
UIImage *imageToprocess = [info objectForKey:UIImagePickerControllerOriginalImage];
NSLog(#"image width %f", imageToprocess.size.width);
NSLog(#"image height %f", imageToprocess.size.height);
I see the following result on console.. But how is this possible. the dimensions of the image is exceeding the dimension of the iPhone screen size.. (which is 320, 568)
UsingTesseractOCR[524:60b] image width 2448.000000
2013-12-17 16:02:18.962 UsingTesseractOCR[524:60b] image height 3264.000000
Can anybody help me out here?? I have gone through several questions here, but did not understand how to do it.
Please help..
Refer this sample code for image capturing and cropping.
https://github.com/kishikawakatsumi/CropImageSample
For creating overlay, first create a custom view (of full dimensions of camera preview) and add an transparent image with just a rectangle in its background. use this view as overlay view.
myview =[[UIImageView alloc]init];
myview.frame=CGRectMake(0, 0, 320, 431);
// why 431? bcoz height = height of device - height of tabbar present in the
bottom for camera controls of picker
//for iphone 4 ,480-49
myview.backgroundColor =[UIColor clearColor];
myview.opaque = NO;
myview.image =[UIImage imageNamed:#"A45Box.png"];
myview.userInteractionEnabled =YES;
note that you create a background image appropriately (means dimensions). You can also draw rectangle programmatically but this is much easy way.
Secondly, talking about your cropping issue, you have to get your hands dirty....Try these links for help
https://github.com/iosdeveloper/ImageCropper
https://github.com/barrettj/BJImageCropper
https://github.com/ardalahmet/SSPhotoCropperViewController

Crop an area of oversized image to what is currently showing onscreen

I have an oversized image loaded in a image view that goes out of bounds both vertically and horizontally.
The end user can scroll around the image (the oversized imageview is in a scrollview) and when they find an area that they like I would like to crop out the area of the image that is shown on the screen. (much like a screenshot but only of the imageview.image I'm then going to put that into a different Imageview.
I can't seem to work out how to accomplish the "screenshot" of the area of the image view's image that is currently showing on the screen.
You can use CGImageCreateWithImageInRect to create a subimage of the displayed image. Use contentOffset and the scrollViews bounds to create the rect from which you want to create the image.
CGRect rect = CGRectMake(scrollView.contentOffset.x, scrollView.contentOffset.y, CGRectGetWidth(scrollView.bounds), CGRectGetHeight(scrollView.bounds));
CGImageRef subImageRef = CGImageCreateWithImageInRect([originalImage CGImage], rect);
If you zoom your scrollView you will need to take the zoomLevel into account too.
I ended up using the following code to achieve what I was looking for to grab the image. Thank you to Karl for his input and a thank you to iNoob whom answer to a previous question [Located here on StackOverflow][1] I used for mine.
Just use the below code to take a "screenshot" just set anything you don't want in the image to.hidden = True; before the code to hide it from the screenshot and set them to .Hidden = FALSE; after the code to bring them back.
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImgePickerView Images taken in landscape stretched when displayed

In the UIImagePicker the user takes photos, then the photos are saved, and loaded into a tableview, now when the images are taken normally (portrait) they are a perfect size in the image view because this is how I set it. But when the user takes an image with the device in landscape, the image looks skewed and looks very distorted. (See picture)
Top is portrait picture, bottom is landscape
So does anyone have any suggestions on how this can be done?
Any help would be amazing
If it is taken in Landscape, then you show it another frame with size width > height. Or try using the following code and see if it improves something.
imageViewTemp.clipsToBounds = YES;
imageViewTemp.contentMode = UIViewContentModeScaleAspectFit;
The UIImageView stretches images to fit its size. This is what you are seeing. To stop it, you might change the size of the image view, like so:
CGRect newFrame = CGRectMake(imageView.frame.origin.x,
imageView.frame.origin.y,
image.size.width,
image.size.height);
imageView.frame = newFrame;

Crop UIImage from a transformed UIImageView

I am letting the user capture an image from the camera or picking one from the library.
This image I display in an UIImageView.
The user can now scale and position the image within a bounding box, exactly like you would do using the UIImagePickerController when allowsEditing is set to YES.
When the user is satisfied with the result and taps Done I would like to produce a cropped UIImage.
The problem arises when using CGImageCreateWithImageInRect as this does not take the scaling into account. The transform is applied to the imageView like this:
CGAffineTransform transform = CGAffineTransformScale(self.imageView.transform, newScale, newScale);
[self.imageView setTransform:transform];
Using a gestureRecognizer.
I assume what is happening is; the UIImageView is scaled and moved, it then applies the UIViewContentModeScaleAspectFit to the UIImage is holds and when I ask it to crop the image, it does exactly that - whit no regards to the scaling positioning. The reason I think this, is that if I don't scale or move the image but just tap Done straight away the cropping works.
I crop the image like this:
- (UIImage *)cropImage:(UIImage*) img toRect:(CGRect)rect {
CGFloat scale = [[UIScreen mainScreen] scale];
if (scale>1.0) {
rect = CGRectMake(rect.origin.x*scale , rect.origin.y*scale, rect.size.width*scale, rect.size.height*scale);
}
CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], rect);
UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.imageView.image.scale orientation:self.imageView.image.imageOrientation];
// UIImage *result = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return result;
}
Passing in a cropRect from a view that is a subView of my main view (the square overlay box, like in UIImagePickerController). Main UIView has a UIImageView that gets scaled and a UIView that displays the crop rectangle.
How can I get the "what you see is what you get" cropping and which factors must I take into account. Or maybe suggestions if I should implemented the hierarchy or scaling differently.
Try a simple trick. Apple has got samples on its site to show how to zoom into a photo using code. Once done zooming, using graphic context take the frame size of the bounding view, and take the image with that. Eg Uiview contains scroll view which has the zoomed image. So the scrollview zooms and so does your image, now take the frame size of your bounding UIview, and create an image context out of it and then save that as a new image. Tell me if that makes sense.
Cheers :)

Resources