Capture still image be stretched with Cocoa Touch AVFoundation framework - iphone

I must capture still image with cocoa touch AVFoundation framework,but I found that captured image be stretched.
I have configured the captureSession as these:
[self setPreviewLayer:[[AVCaptureVideoPreviewLayer alloc] initWithSession:[self captureSession]]];
self.captureSession.sessionPreset=AVCaptureSessionPresetHigh;
[[self previewLayer] setVideoGravity:AVLayerVideoGravityResizeAspectFill];
And use these code to capture image:
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
{
if(error)
NSLog(#"error=%#",error);
else
{
if (imageDataSampleBuffer != NULL) {
NSData *imageData=[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image=[[UIImage alloc] initWithData:imageData];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
CGSize screenSize=CGSizeMake(screenWidth, screenHeight);
NSLog(#"screen.width=%f,screen.height=%f",screenWidth,screenHeight);
UIGraphicsBeginImageContextWithOptions(screenSize, NO, 0.0f);
// This is where we resize captured image
[(UIImage *)image drawInRect:CGRectMake(0, 0, screenWidth, screenHeight)];
CGSize imageSize=[ImageUtility getImageSize:image];
NSLog(#"image.width=%f,image.height=%f",imageSize.width,imageSize.height);
// Save the results directly to the image view property
UIImage *toSaveImage=UIGraphicsGetImageFromCurrentImageContext();
imageSize=[ImageUtility getImageSize:toSaveImage];
NSLog(#"combine.width=%f,combine.height=%f",imageSize.width,imageSize.height);
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(toSaveImage, nil, nil, nil);
}
}
}];
}
This result output:
013-08-29 09:30:06.182 WatermarkCamera[6882:907] screen.width=320.000000,screen.height=480.000000
2013-08-29 09:30:07.208 WatermarkCamera[6882:907] image.width=1280.000000,image.height=720.000000
2013-08-29 09:30:07.238 WatermarkCamera[6882:907] combine.width=640.000000,combine.height=960.000000
The result output image stretched.How to fix the stretched image?Any suggestions should be appreciated.

I think I shouldn't draw image with the size of screen.I should draw image with the size of image.
I have defined new method to scale image to new width
+(UIImage*)imageWithImage: (UIImage*) sourceImage scaledToWidth: (float) i_width;
Now I called this method
UIImage *newImage=[ImageUtility imageWithImage:image scaledToWidth:screenWidth];
[newImage drawInRect:CGRectMake(0, 0, newImage.size.width, newImage.size.height)];
Finally write the new image to photo album.The new image doesn't stretch.

Related

Get the image of Web Page

I'm trying to capture the full image of the web page..
But its showing the blank image..
what should i do to get the complete Web Page Image?
I have tried with
CGSize overallSize = [WebPageImage sizeThatFits:CGSizeZero];
UIGraphicsBeginImageContext(WebPageImage.scrollView.contentSize);
WebPageImage.bounds = CGRectMake(0, 0, overallSize.width, overallSize.height);
while (WebPageImage.loading) {
[NSThread sleepForTimeInterval:0.1];
}
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,(unsigned long)NULL), ^(void) {
UIImageWriteToSavedPhotosAlbum(viewImage, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
});
Please suggest some solution..
WebPageImage is UIWebView..
UIGraphicsBeginImageContextWithOptions(WebPageImage.bounds.size, WebPageImage.opaque, 0.0);
[WebPageImage.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
use this function according to your need. below code will give you snapshot of whole webpage
- (UIImage *) imageFromWebView:(UIWebView *)view
{
// tempframe to reset view size after image was created
CGRect tmpFrame = view.frame;
// set new Frame
CGRect aFrame = view.frame;
aFrame.size.height = [view sizeThatFits:[[UIScreen mainScreen] bounds].size].height;
aFrame.size.width = [view sizeThatFits:[[UIScreen mainScreen] bounds].size].width;
view.frame = aFrame;
// do image magic
UIGraphicsBeginImageContext([view sizeThatFits:[[UIScreen mainScreen] bounds].size]);
CGContextRef resizedContext = UIGraphicsGetCurrentContext();
[self.thmbWebView.layer renderInContext:resizedContext];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// reset Frame of view to origin
view.frame = tmpFrame;
return image;
}
Try this:
[WebPageImage.layer renderInContext:UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
try to capture that image with my bellow method...
-(IBAction)captureScreen:(id)sender
{
UIGraphicsBeginImageContext(webview.frame.size);
[webview.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
}
Also see my another answer from this link.. howe-to-capture-uiview-top-uiview

How to save two picture, which allow 1 of them rotation, zoom & move

as per my title, i have a 2 picture which i will like to save it as one photo.
one of the photo allow user to gesture such as rotate, zoom and move around.
how do i save user moved and rotated picture ?
screen shot of the phone saved image
the code below are referred from
How to combine/ merge 2 images into 1
UIImage *image = nil;
CGSize newImageSize = CGSizeMake(cropImage.frame.size.width, cropImage.frame.size.height);
if (UIGraphicsBeginImageContextWithOptions != NULL) {
UIGraphicsBeginImageContextWithOptions(newImageSize, NO, [[UIScreen mainScreen] scale]);
} else {
UIGraphicsBeginImageContext(newImageSize);
}
// Draw image1
[maskImage.image drawInRect:CGRectMake(0,0, maskImage.frame.size.width,maskImage.frame.size.height)];
// Draw image2
[cropImage.image drawInRect:CGRectMake(cropImage.frame.origin.x, cropImage.frame.origin.y, cropImage.frame.size.width, cropImage.frame.size.height)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
Try this piece of code
//Hide your views here like save button
CGRect screenRect = [[UIScreen mainScreen] bounds];
UIGraphicsBeginImageContext(screenRect.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, self, nil, nil);
//Show again your hidden views here like save button

why some UIimages don't show up in iphone

hi I am currently developing a small app on ios 4.3 , using objective c
as part of the app I need to manipulate an Image that I have downloaded from the web.
the following code shows up a missing image:
(the original is in a class but I just put this together as a test scenario so that it could be easily copy pasted)
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadImage:#"http://www.night-net.net/images/ms/microsoft_vista_home_basic.jpg"];
[self getCroped:CGRectMake(10, 50, 80, 160)];
[self getCroped:CGRectMake(90, 50, 80, 80)];
[self getCroped:CGRectMake(90, 130, 40, 80)];
[self getCroped:CGRectMake(130, 130, 40, 40)];
[self getCroped:CGRectMake(130, 170, 40, 40)];
}
-(void) loadImage : (NSString*) url
{
_data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
}
-(UIImageView*) getCroped:(CGRect) imageSize{
UIImage *temp = [[UIImage alloc] initWithData:_data];
UIImage *myImage = [self resizedImage:temp and:CGSizeMake(160,160) interpolationQuality:kCGInterpolationHigh];
UIImage *image = [self croppedImage:myImage and:imageSize];
UIImageView *imageView = [[UIImageView alloc] init];
imageView.image = image;
imageView.frame = imageSize;
[[self view] addSubview:imageView];
return imageView;
}
- (UIImage *)croppedImage:(UIImage*) image and: (CGRect)bounds {
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], bounds);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return croppedImage;
}
- (UIImage *)resizedImage:(UIImage*) image and:(CGSize)newSize interpolationQuality:(CGInterpolationQuality)quality {
BOOL drawTransposed = NO;
return [self resizedImage:image
and:newSize
transform:[self transformForOrientation:newSize]
drawTransposed:drawTransposed
interpolationQuality:quality];
}
// Returns a copy of the image that has been transformed using the given affine transform and scaled to the new size
// The new image's orientation will be UIImageOrientationUp, regardless of the current image's orientation
// If the new size is not integral, it will be rounded up
- (UIImage *)resizedImage:(UIImage*) image and:(CGSize)newSize
transform:(CGAffineTransform)transform
drawTransposed:(BOOL)transpose
interpolationQuality:(CGInterpolationQuality)quality {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGRect transposedRect = CGRectMake(0, 0, newRect.size.height, newRect.size.width);
CGImageRef imageRef = image.CGImage;
// Build a context that's the same dimensions as the new size
CGContextRef bitmap = CGBitmapContextCreate(NULL,
newRect.size.width,
newRect.size.height,
CGImageGetBitsPerComponent(imageRef),
0,
CGImageGetColorSpace(imageRef),
CGImageGetBitmapInfo(imageRef));
// Rotate and/or flip the image if required by its orientation
CGContextConcatCTM(bitmap, transform);
// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(bitmap, quality);
// Draw into the context; this scales the image
CGContextDrawImage(bitmap, transpose ? transposedRect : newRect, imageRef);
// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(bitmap);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
// Clean up
CGContextRelease(bitmap);
CGImageRelease(newImageRef);
return newImage;
}
// Returns an affine transform that takes into account the image orientation when drawing a scaled image
- (CGAffineTransform)transformForOrientation:(CGSize)newSize {
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformTranslate(transform, newSize.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
return transform;
}
at first I thought this is caused by a lack of memory, but I have tested for that and that doesnt seem to be the problem,thanks in advance ofir
I've had issues in the past with images not appearing within UIWebViews if they contain unicode characters in the filename. I wonder if this might be the same thing. Try renaming your image?
doing this should be possible and low on memory cost as I did the same test,using flash to create an iphone app that does the same thing, and it works.
but I would much prefer using objective c so the question still stands

Image is rotated 90 degrees when using clipToMask

I am trying to clip a portion of an image I take with a camera. Here's my clipping code:
- (UIImage*) maskImage:(UIImage *)image {
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
UIImage *maskImage = [UIImage imageNamed:#"mask3.png"];
CGImageRef maskImageRef = [maskImage CGImage];
// create a bitmap graphics context the size of the image
CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
if (mainViewContentContext==NULL)
return NULL;
CGFloat ratio = 0;
ratio = maskImage.size.width/ image.size.width;
if(ratio * image.size.height < maskImage.size.height) {
ratio = maskImage.size.height/ image.size.height;
}
CGRect rect1 = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
CGRect rect2 = {{-((image.size.width*ratio)-maskImage.size.width)/2 , -((image.size.height*ratio)-maskImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}};
CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);
// Create CGImageRef of the main view bitmap content, and then
// release that bitmap context
CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
CGContextRelease(mainViewContentContext);
UIImage *theImage = [UIImage imageWithCGImage:newImage];
CGImageRelease(newImage);
// return the image
return theImage;
}
I am calling above method in my captureNow method in my viewcontroller. I am using AVFoundation to capture still image:
-(void) captureNow
{
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in stillImageOutput.connections)
{
for (AVCaptureInputPort *port in [connection inputPorts])
{
if ([[port mediaType] isEqual:AVMediaTypeVideo] )
{
videoConnection = connection;
break;
}
}
if (videoConnection) { break; }
}
NSLog(#"about to request a capture from: %#", stillImageOutput);
[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
{
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
[testImageView setImage:[self maskImage:image]];
self.firstPieceView.frame = CGRectMake(0, 0, 320, 480);
self.firstPieceView.contentMode = UIViewContentModeScaleAspectFill;
// self.firstPieceView.image = image;
// [firstPieceView setNeedsDisplay];
NSLog(#"self.firstPiece.frame is %#", NSStringFromCGRect(self.firstPieceView.frame));
// [myView becomeFirstResponder];
}];
self.previewParentView.hidden = YES;
self.photoBtn.hidden=YES;
self.imageMask.hidden = NO;
//add the gesture after taking the first image.
[myView addGestureRecognizersToPiece:self.myView];
}
For some reason, my image is always rotated 90 degrees when I clip it. Does anyone know why and how to fix this? Thanks in advance.
Here alternative solution to rotate image to 90 degrees ,its code is bellow...
yourImageView.transform = CGAffineTransformMakeRotation(3.14159265/2);
when you want to share or save the picture at that time just rotate the Image With 90 Degrees and also if Required then 180 degree....
this is alternate solution if i got any other Idea then i will post again...
hope,this help you...
:)

Crop a UIImage from the Center outwards?

I am making a camera app which includes digital zoom. I have a slider (zoomSlider) that has a minimum value of 1 and a maximum value of 4. When the user taps the camera button, it takes a picture, and then I crop it for the zooming. I have two problems:
How do I crop the exact middle of the image? (eg. 2x zoom, Rect would be centered with dimensions of 600x800 (for iPhone 2G/3G))
When I do this, it rotates the image. I make up for it by rotating the UIImageView it's in, but this causes a portrait picture to become landscape and vice versa.
Here is my code:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
if ([mediaType isEqualToString:#"public.image"]){
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
CGRect clippedRect = CGRectMake(600, 450, image.size.width/zoomSlider.value, image.size.height/zoomSlider.value);
UIImage *cropped = [self imageByCropping:image toRect:clippedRect];
CGRect croppedImageSize = CGRectMake(0, 0, image.size.width/zoomSlider.value, image.size.height/zoomSlider.value);
[cropped drawInRect:croppedImageSize];
zoomPhoto.frame = croppedImageSize;
zoomPhoto.image = cropped;
CGAffineTransform rotateTransform = CGAffineTransformRotate(CGAffineTransformIdentity,
RADIANS(90.0));
zoomPhoto.transform = rotateTransform;
}
- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
CGFloat newWidth = image.size.width/zoomSlider.value;
CGFloat newHeight = image.size.height/zoomSlider.value;
CGRect clippedRect = CGRectMake((image.size.width-newWidth)/2, (image.size.height-newHeight)/2, newWidth, newHeight);
Remove this to not rotate the image:
CGAffineTransform rotateTransform = CGAffineTransformRotate(CGAffineTransformIdentity,RADIANS(90.0));
zoomPhoto.transform = rotateTransform;