Get zoomed image from UIImageView - iphone

I am using a UIImageview inside a UIScrollView to let users pinch and zoom the image. I now want to get the image which the user has modified (small or zoomed in). How can I do this?
Thanks.
OK, am trying something new now. Can I get a thumbnail from an image from somewhere in between?
I can get the thumbnail from (0,0) for a fixed size. Can I get it from say (10, 20) or (30, 30)? Thanks again.
I tried using CGImageCreateWithImageInRect with a rect having these values for x and y. But it gives me an image from point 0,0

When you zoom UIImageView object inside UIScrollView, you change only UIImageView frame, but UIImage in image property remains unchanged.
if you only want to show this image scaled in some other UIImageView, you should not change UIImage size, just set your new UIImageView frame same as frame of zoomed UIImageView from UIScrollView and use same image:
UIImageView * ImageViewOnScroll;
//set image and zoom it
...
UIImageView * newImageView = [[UIImageView alloc] initWithImage:ImageViewOnScroll.image];
newImageView.frame = ImageViewOnScroll.frame;
if for some reason you want to create new UIImage with changed size you can do it for example with following simple method:
UIImage * resizeImage(UIImage * img, CGSize newSize){
UIGraphicsBeginImageContext(newSize);
//or other CGInterpolationQuality value
CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationDefault);
[img drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

I solved it by creating a tiny UIImage extension (Swift 5.2 compatible) that works perfectly when you have UIImageView embedded in UIScrollView:
extension UIImage {
func crop(from scrollView: UIScrollView) -> UIImage? {
let zoom: CGFloat = 1.0 / scrollView.zoomScale
let xOffset: CGFloat = (size.width / scrollView.contentSize.width) * scrollView.contentOffset.x
let yOffset: CGFloat = (size.height / scrollView.contentSize.height) * scrollView.contentOffset.y
let cropRect = CGRect(xOffset * scale, yOffset * scale, size.width * zoom * scale, size.height * zoom * scale)
guard let croppedImageRef = cgImage?.cropping(to: cropRect) else { return nil }
let croppedImage = UIImage(cgImage: croppedImageRef, scale: scale, orientation: imageOrientation)
return croppedImage
}
}
Use it to get zoomed part of the image:
let croppedImage = sourceImage.crop(from: scrollView)

Related

Cropping an image from the top in Swift

I am trying to crop this image, which is a SKSpriteNode:
I am trying to crop this image from the top, so that I maintain the bottom semi circle of this shape. For instance, it'd be cropped to this:
So I use these two methods to accomplish this task:
func recalculateScore() {
currentScore -= decreaseRate
let image = UIImage(cgImage: (vial.texture?.cgImage())!)
vial.texture = SKTexture(image: cropBottomImage(image: image))
}
func cropBottomImage(image: UIImage) -> UIImage {
let height = CGFloat(image.size.height / 3)
let rect = CGRect(x: 0, y: image.size.height - height, width: image.size.width, height: height)
return cropImage(image: image, toRect: rect)
}
func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage {
let imageRef:CGImage = image.cgImage!.cropping(to: rect)!
let croppedImage:UIImage = UIImage(cgImage:imageRef)
return croppedImage
}
However, this leads to this result:
It is as if it was being compressed. I think my issue might be in this line:
let rect = CGRect(x: 0, y: image.size.height - height, width: image.size.width, height: height)
Does the CGRect coordinate of (0,0) lie within the top most left corner? I am a bit confused on what the x and y parameters for the CGRect mean?
Resize your sprite, what is happening is the cropped texture is stretching to fill the sprite, and since you only crop vertically, it will only stretch vertically
func recalculateScore() {
currentScore -= decreaseRate
let image = UIImage(cgImage: (vial.texture?.cgImage())!)
vial.texture = SKTexture(image: cropBottomImage(image: image))
vial.size = vial.texture.size
}

Is it possible to change the size of the image you get from using the camera thru imagePicker?

When I try to change the property currently, I am getting a error that the size is a "Get Only Property." Anyone know a way around this?
you can try the following (I didn't run it yet, pretty sure it works..)
let imagePickerView: UIView = self.imagePicker.view
let cameraViewFrame: CGRect = CGRectMake(0, self.overlay.topBarHeight,
self.view.bounds.size.width,
self.view.bounds.size.height -self.overlay.topBarHeight - self.overlay.bottomBarHeight);
imagePickerView.frame = cameraViewFrame
Good luck :)
What we can do is to draw a new UIImage instead. The code below is a function to scale the image passed in. And after the image has been scaled, the size changes.
extension UIImage {
class func scaleImage(image:UIImage, scaleFloat:CGFloat) -> UIImage{
let size = CGSizeMake(image.size.width * scaleFloat, image.size.height * scaleFloat)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
var transform = CGAffineTransformIdentity
transform = CGAffineTransformScale(transform, scaleFloat, scaleFloat)
CGContextConcatCTM(context, transform)
image.drawAtPoint(CGPointMake(0, 0))
let newimg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newimg
}
}
Here is the example code to scale the image to 150x150. But these codes only helps the square image. If it is not square, you can test for what will happen.
extension UIImage {
class func scaleImgTo150x150(image:UIImage) -> UIImage{
let scale:CGFloat
if image.size.width > image.size.height{
scale = 150/image.size.width
}
else{
scale = 150/image.size.height
}
return UIImage.scaleImage(image, scaleFloat: scale)
}
}

How to save a UIImage to Parse

I've taken an image and converted it to the jpeg format as such
let jpgImage = UIImageJPEGRepresentation(image1, 0.5)
Next I want to upload this image to Parse as a object part of a PFUser. When ever I try this I get the error
[Error]: The object is too large -- should be less than 128 kB
I don't know how to fix this error and just sign up the user. Thanks for any help or advice!
Objects are limited to 128kb as the error states, if your image is larger than that as it is you can choose to shrink it by using the function below.
func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
} else {
newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRectMake(0, 0, newSize.width, newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
Use of the above function, you can resize your image as dynamics
dimension.Here as above code resize image of 200*200. By calling the
below function.
self.ResizeImage(UIImage(named: "yourImageName")!, targetSize: CGSizeMake(200.0, 200.0))
Source code from here.
So start by checking the image size by:
let sizeOfImage = image?.size
if let image = image {
let sizeOfImage = image.size
// Check the size here and resize if needed
}

Resize UIImage by keeping Aspect ratio and width

I seen in many posts for resizing the image by keeping aspect ratio. These functions uses the fixed points(Width and Height) for RECT while resizing. But in my project, I need to resize the view based on the Width alone, Height should be taken automatically based on the aspect ratio.
anyone help me to achieve this.
The method of Srikar works very well, if you know both height and width of your new Size.
If you for example know only the width you want to scale to and don't care about the height you first have to calculate the scale factor of the height.
+(UIImage*)imageWithImage: (UIImage*) sourceImage scaledToWidth: (float) i_width
{
float oldWidth = sourceImage.size.width;
float scaleFactor = i_width / oldWidth;
float newHeight = sourceImage.size.height * scaleFactor;
float newWidth = oldWidth * scaleFactor;
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
[sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
If you don't happen to know if the image will be portrait or landscape (e.g user takes pic with camera), I created another method that takes max width and height parameters.
Lets say you have a UIImage *myLargeImage which is a 4:3 ratio.
UIImage *myResizedImage = [ImageUtilities imageWithImage:myLargeImage
scaledToMaxWidth:1024
maxHeight:1024];
The resized UIImage will be 1024x768 if landscape; 768x1024 if portrait. This method will also generate higher res images for retina display.
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size {
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]);
} else {
UIGraphicsBeginImageContext(size);
}
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
+ (UIImage *)imageWithImage:(UIImage *)image scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height {
CGFloat oldWidth = image.size.width;
CGFloat oldHeight = image.size.height;
CGFloat scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;
CGFloat newHeight = oldHeight * scaleFactor;
CGFloat newWidth = oldWidth * scaleFactor;
CGSize newSize = CGSizeMake(newWidth, newHeight);
return [ImageUtilities imageWithImage:image scaledToSize:newSize];
}
Best answer Maverick 1st's correctly translated to Swift (working with latest swift 3):
func imageWithImage (sourceImage:UIImage, scaledToWidth: CGFloat) -> UIImage {
let oldWidth = sourceImage.size.width
let scaleFactor = scaledToWidth / oldWidth
let newHeight = sourceImage.size.height * scaleFactor
let newWidth = oldWidth * scaleFactor
UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
sourceImage.draw(in: CGRect(x:0, y:0, width:newWidth, height:newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
thanks #Maverick1st the algorithm, I implemented it to Swift, in my case height is the input parameter
class func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
This method is a category on UIImage. Does scale to fit in few lines of code using AVFoundation.
Don't forget to import #import <AVFoundation/AVFoundation.h>.
#implementation UIImage (Helper)
- (UIImage *)imageScaledToFitToSize:(CGSize)size
{
CGRect scaledRect = AVMakeRectWithAspectRatioInsideRect(self.size, CGRectMake(0, 0, size.width, size.height));
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
[self drawInRect:scaledRect];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
#end
Swift 5 version of aspect-fit-to-height, based on answer by #János
Uses the modern UIGraphicsImageRenderer API, so a valid UIImage is guaranteed to return.
extension UIImage
{
/// Given a required height, returns a (rasterised) copy
/// of the image, aspect-fitted to that height.
func aspectFittedToHeight(_ newHeight: CGFloat) -> UIImage
{
let scale = newHeight / self.size.height
let newWidth = self.size.width * scale
let newSize = CGSize(width: newWidth, height: newHeight)
let renderer = UIGraphicsImageRenderer(size: newSize)
return renderer.image { _ in
self.draw(in: CGRect(origin: .zero, size: newSize))
}
}
}
You can use this in conjunction with a (vector-based) PDF image asset, to preserve quality at any render size.
The simplest way is to set the frame of your UIImageView and set the contentMode to one of the resizing options.
The code goes like this - This can be used as an utility method -
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Just import AVFoundation and use AVMakeRectWithAspectRatioInsideRect(CGRectCurrentSize, CGRectMake(0, 0, YOUR_WIDTH, CGFLOAT_MAX)
Well, we have few good answers here for resizing image, but I just modify as per my need. hope this help someone like me.
My Requirement was
If image width is more than 1920, resize it with 1920 width and maintaining height with original aspect ratio.
If image height is more than 1080, resize it with 1080 height and maintaining width with original aspect ratio.
if (originalImage.size.width > 1920)
{
CGSize newSize;
newSize.width = 1920;
newSize.height = (1920 * originalImage.size.height) / originalImage.size.width;
originalImage = [ProfileEditExperienceViewController imageWithImage:originalImage scaledToSize:newSize];
}
if (originalImage.size.height > 1080)
{
CGSize newSize;
newSize.width = (1080 * originalImage.size.width) / originalImage.size.height;
newSize.height = 1080;
originalImage = [ProfileEditExperienceViewController imageWithImage:originalImage scaledToSize:newSize];
}
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Thanks to #Srikar Appal , for resizing I have used his method.
You may like to check this as well for resize calculation.
Programmatically:
imageView.contentMode = UIViewContentModeScaleAspectFit;
Storyboard:
If somebody needs this solution in Swift 5:
private func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
image.draw(in:CGRect(x:0, y:0, width:newWidth, height:newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
To improve on Ryan's answer:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size {
CGFloat oldWidth = image.size.width;
CGFloat oldHeight = image.size.height;
//You may need to take some retina adjustments into consideration here
CGFloat scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;
return [UIImage imageWithCGImage:image.CGImage scale:scaleFactor orientation:UIImageOrientationUp];
}
Ryan's Solution #Ryan
in swift code
use:
func imageWithSize(image: UIImage,size: CGSize)->UIImage{
if UIScreen.mainScreen().respondsToSelector("scale"){
UIGraphicsBeginImageContextWithOptions(size,false,UIScreen.mainScreen().scale);
}
else
{
UIGraphicsBeginImageContext(size);
}
image.drawInRect(CGRectMake(0, 0, size.width, size.height));
var newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
//Summon this function VVV
func resizeImageWithAspect(image: UIImage,scaledToMaxWidth width:CGFloat,maxHeight height :CGFloat)->UIImage
{
let oldWidth = image.size.width;
let oldHeight = image.size.height;
let scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;
let newHeight = oldHeight * scaleFactor;
let newWidth = oldWidth * scaleFactor;
let newSize = CGSizeMake(newWidth, newHeight);
return imageWithSize(image, size: newSize);
}
extension UIImage {
/// Returns a image that fills in newSize
func resizedImage(newSize: CGSize) -> UIImage? {
guard size != newSize else { return self }
let hasAlpha = false
let scale: CGFloat = 0.0
UIGraphicsBeginImageContextWithOptions(newSize, !hasAlpha, scale)
draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// Returns a resized image that fits in rectSize, keeping it's aspect ratio
/// Note that the new image size is not rectSize, but within it.
func resizedImageWithinRect(rectSize: CGSize) -> UIImage? {
let widthFactor = size.width / rectSize.width
let heightFactor = size.height / rectSize.height
var resizeFactor = widthFactor
if size.height > size.width {
resizeFactor = heightFactor
}
let newSize = CGSize(width: size.width / resizeFactor, height: size.height / resizeFactor)
let resized = resizedImage(newSize: newSize)
return resized
}
}
When scale is set to 0.0, the scale factor of the main screen is used, which for Retina displays is 2.0 or higher (3.0 on the iPhone 6 Plus).
In Swift 3 there are some changes.
Here is an extension to UIImage:
public extension UIImage {
public func resize(height: CGFloat) -> UIImage? {
let scale = height / self.size.height
let width = self.size.width * scale
UIGraphicsBeginImageContext(CGSize(width: width, height: height))
self.draw(in: CGRect(x:0, y:0, width:width, height:height))
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage
}
}
Calculates the best height of the image for available width.
import Foundation
public extension UIImage {
public func height(forWidth width: CGFloat) -> CGFloat {
let boundingRect = CGRect(
x: 0,
y: 0,
width: width,
height: CGFloat(MAXFLOAT)
)
let rect = AVMakeRect(
aspectRatio: size,
insideRect: boundingRect
)
return rect.size.height
}
}
Zeeshan Tufail and Womble answers in Swift 5 with small improvements.
Here we have extension with 2 functions to scale image to maxLength of any dimension and jpeg compression.
extension UIImage {
func aspectFittedToMaxLengthData(maxLength: CGFloat, compressionQuality: CGFloat) -> Data {
let scale = maxLength / max(self.size.height, self.size.width)
let format = UIGraphicsImageRendererFormat()
format.scale = scale
let renderer = UIGraphicsImageRenderer(size: self.size, format: format)
return renderer.jpegData(withCompressionQuality: compressionQuality) { context in
self.draw(in: CGRect(origin: .zero, size: self.size))
}
}
func aspectFittedToMaxLengthImage(maxLength: CGFloat, compressionQuality: CGFloat) -> UIImage? {
let newImageData = aspectFittedToMaxLengthData(maxLength: maxLength, compressionQuality: compressionQuality)
return UIImage(data: newImageData)
}
}
This one was perfect for me. Keeps aspect ratio and takes a maxLength. Width or Height will not be more than maxLength
-(UIImage*)imageWithImage: (UIImage*) sourceImage maxLength: (float) maxLength
{
CGFloat scaleFactor = maxLength / MAX(sourceImage.size.width, sourceImage.size.height);
float newHeight = sourceImage.size.height * scaleFactor;
float newWidth = sourceImage.size.width * scaleFactor;
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
[sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
I have solved it in a much simpler way
UIImage *placeholder = [UIImage imageNamed:#"OriginalImage.png"];
self.yourImageview.image = [UIImage imageWithCGImage:[placeholder CGImage] scale:(placeholder.scale * 1.5)
orientation:(placeholder.imageOrientation)];
multiplier of the scale will define the scalling of the image,more the multiplier smaller the image. so You can check what fits your screen.
Or you can also get the multiplire by dividing imagewidth/screenwidth.

Return a subimage from a UIImage

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?
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!
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!)
In Swift 4, taking into account screen scale (otherwise your new image will be too large):
let img = UIImage(named: "existingImage")!
let scale = UIScreen.main.scale
let dy: CGFloat = 6 * scale // say you want 6pt from bottom
let area = CGRect(x: 0, y: img.size.height * scale - dy, width: img.size.width * scale, height: dy)
let crop = img.cgImage!.cropping(to: area)!
let subImage = UIImage(cgImage: crop, scale: scale, orientation:.up)