Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop image from bottom programmatically

I am working on the custom camera application. Things are working good.

But I got into the problem while cropping the image from bottom. i.e. cropped image is having exact same width as the original image but height will be 1/3 of the original image and it must start from the bottom.

For Example Like this is the full image I need the red part only

like image 390
BornShell Avatar asked Oct 11 '16 06:10

BornShell


3 Answers

Swift 3 solution:

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)
}

Helper method for cropping with a 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
}
like image 80
alexburtnik Avatar answered Nov 12 '22 10:11

alexburtnik


this is almost Alexburtnik's answer

but just to mention that UIImage.size is the logical size (in "points")

however, CGImage.cropping() used the actual dimension (in "pixels")

therefore, if you use a image with @2x or @3x modifiers, you will find the cropping is actually half or one third of the expectation.

so when you crop, you may consider multiplying the rect by the "scale" property of the image first, like the following:

func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage? {
    var rect = rect
    rect.size.width = rect.width * image.scale
    rect.size.height = rect.height * image.scale

    guard let imageRef = image.cgImage?.cropping(to: rect) else {
        return nil
    }

    let croppedImage = UIImage(cgImage:imageRef)
    return croppedImage
}
like image 39
royl8 Avatar answered Nov 12 '22 12:11

royl8


As an extension to UIImage:

import UIKit

extension UIImage {
    func crop(to rect: CGRect) -> UIImage? {
        // Modify the rect based on the scale of the image
        var rect = rect
        rect.size.width = rect.size.width * self.scale
        rect.size.height = rect.size.height * self.scale

        // Crop the image
        guard let imageRef = self.cgImage?.cropping(to: rect) else {
            return nil
        }

        return UIImage(cgImage: imageRef)
    }
}

Usage:

let myImage = UIImage(named:"myImage.png")    
let croppedRect = CGRect(x: 0, y: 0, width: newWidth, height: newHeight)
let croppedImage = myImage.crop(to: croppedRect)
like image 1
jackofallcode Avatar answered Nov 12 '22 10:11

jackofallcode