ios


CGImageCreateWithImageInRect() returning nil


I'm trying to crop an image into a square, but once I actually try to do the crop by using CGImageCreateWithImageInRect(), this line crashes. I set breakpoints and made sure that the arguments passed into this function are not nil.
I'm fairly new to programming and Swift, but have searched around and haven't found any solution to my problem.
The failure reason:
fatal error: unexpectedly found nil while unwrapping an Optional value
func cropImageToSquare(imageData: NSData) -> NSData {
let image = UIImage(data: imageData)
let contextImage : UIImage = UIImage(CGImage: image!.CGImage!)
let contextSize: CGSize = contextImage.size
let imageDimension: CGFloat = contextSize.height
let posY : CGFloat = (contextSize.height + (contextSize.width - contextSize.height)/2)
let rect: CGRect = CGRectMake(0, posY, imageDimension, imageDimension)
// error on line below: fatal error: unexpectedly found nil while unwrapping an Optional value
let imageRef: CGImageRef = CGImageCreateWithImageInRect(contextImage.CGImage, rect)!
let croppedImage : UIImage = UIImage(CGImage: imageRef, scale: 1.0, orientation: image!.imageOrientation)
let croppedImageData = UIImageJPEGRepresentation(croppedImage, 1.0)
return croppedImageData!
}
Your code uses a lot of force-unwrapping with !s. I would recommend avoiding this — the compiler is trying to help you write code that won't crash. Use optional chaining with ?, and if let / guard let, instead.
The ! on that particular line is hiding an issue where CGImageCreateWithImageInRect might return nil. The documentation explains that this happens when the rect is not correctly inside the image bounds. Your code works for images in portrait orientation, but not landscape.
Furthermore, there's a convenient function provided by AVFoundation which can automatically find the right rectangle for you to use, called AVMakeRectWithAspectRatioInsideRect. No need to do the calculations manually :-)
Here's what I would recommend:
import AVFoundation
extension UIImage
{
func croppedToSquare() -> UIImage
{
guard let cgImage = self.CGImage else { return self }
// Note: self.size depends on self.imageOrientation, so we use CGImageGetWidth/Height here.
let boundingRect = CGRect(
x: 0, y: 0,
width: CGImageGetWidth(cgImage),
height: CGImageGetHeight(cgImage))
// Crop to square (1:1 aspect ratio) and round the resulting rectangle to integer coordinates.
var cropRect = AVMakeRectWithAspectRatioInsideRect(CGSize(width: 1, height: 1), boundingRect)
cropRect.origin.x = ceil(cropRect.origin.x)
cropRect.origin.y = ceil(cropRect.origin.y)
cropRect.size.width = floor(cropRect.size.width)
cropRect.size.height = floor(cropRect.size.height)
guard let croppedImage = CGImageCreateWithImageInRect(cgImage, cropRect) else {
assertionFailure("cropRect \(cropRect) was not inside \(boundingRect)")
return self
}
return UIImage(CGImage: croppedImage, scale: self.scale, orientation: self.imageOrientation)
}
}
// then:
let croppedImage = myUIImage.croppedToSquare()

Related Links

Facebook Login Button Throws An Error And Says I Cannot Login
In-app purchase receipt validation, “in_app” field empty
How can we pass the parameters along with block methods in objecitve-c
Apple Remote Push Notifications
Game stops working when restart button clicked
Swift - Create a custom push segue
how to set alpha on Backgroung image using Swift
Livecode revdberr invalid database connection
How to sort an array which contains objects with chars and decimals? [duplicate]
Set the selected Cell without pushing to new viewController
Page view constraints bug
How to rotate and crop iOS CGImage from file
How do I get the value of a UITextfield as characters are being typed in real time?
Any one Know ?? how to get router ip address from mac and iPhone? [closed]
What means iOS Xcode plist warning?
Deleting NSUserdefault Array from a UITableView

Categories

HOME
ffmpeg
clojure
dicom
dynamics-crm-365
jsessionid
azure-web-sites
delphi-xe7
jena
pie-chart
openmodelica
asp.net-mvc-5.2
rgb
next
stackexchange-api
nsmutableattributedstring
gyroscope
stm32f4discovery
git-bash
google-finance
easendmail
hawq
intersystems
sumifs
text-parsing
reformatting
shinydashboard
clappr
bluebird
python-responses
angular2-databinding
apache-commons-httpclient
lync
tensor
querydsl
folly
ecmascript-4
vtable
bezier
plasticscm
gradle-tooling-api
freerdp
phasset
website-hosting
multisite
formstack
xssf
orchestrate
ctl
gcc4.8
okular
soql
html-lists
billing
flying-saucer
android-chips
git-config
printscreen
coldfusion-11
cglib
webtrends
agents-jade
telecommunication
pager
namenode
id3
yapdatabase
radix-sort
samsung-gear
database-tuning-advisor
nominatim
nbug
cbc-mode
bloodhound
gem5
gevent-socketio
emberfire
cordova-cli
openxls
puppet-enterprise
bitrock
formhelper
android-menu
subdirectory
dynamic-data-display
image-scaling
xacml3
jqgrid-php
xml.modify
keymapping
antisamy
sqlprofiler
emitmapper
google-authorship
applaud
mixing
media-manager
quilt
cellphone
springboard
ramaze
facebook-authentication
ssao
blackberry-jde
apache-config
mkmapviewdelegate
seam-conversation
scramble
coords

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App