create image from data cocoa swift 5 - swift

I have a set of Data coming from a request (AlamoFire) as per the image below:
I know it's an image, the size of the data is correct. I'd like to create an image from this and tried:
NSImage(data: result) or
NSImage.init(data:result)
Without success. It is possible to do what I try to achieve?
EDIT: to answer Larme on Self.coverImage:

did you try to use this code snippet?
// Swift
// Image to data
let image = UIImage(named: "sample")
let data = image?.pngData()
let data = image?.jpegData(compressionQuality: 0.9)
// Data to Image
let uiImage: UIImage = UIImage(data: imageData)
// this method is deprecated
var imageData: Data = UIImagePNGRepresentation(image)

Related

cast SKSpriteNode to UIImage

I want to convert a SKSpriteNode into an UIImage.
let testImage = SKSpriteNode(imageNamed: "PlainProject") as! UIImage
but I get a crash on the thread above. Is there another way to do this?
You should get the cgImage of the texture of the sprite first, and then cast it to UIImage:
let testImage = SKSpriteNode(imageNamed: "someImage.png")
let image = UIImage(cgImage: (testImage.texture?.cgImage())!)
or a better version without force-unwraping a cgImage that might be nil:
let image = UIImage()
if testImage.texture?.cgImage() != nil{
image = UIImage(cgImage: (testImage.texture?.cgImage())!)
}
Result (in playground):
That is exactly what my image looks like. Hope this helps!
You can not directly do that.
First of all you need to get texture from SKSpriteNode.
After that you can get image with textureOfNode!.cgImage() as shown in below example:
let testNode = SKSpriteNode(imageNamed: "Spaceship")
let textureOfNode = testNode.texture
let imageFromTexture = UIImage.init(cgImage: textureOfNode!.cgImage())
print(imageFromTexture) //<UIImage: 0x61000008afa0>, {394, 347}

Making a GIF from images using Swift (macOS)

I was wondering if there was a way to convert an array of NSImages using Swift in macOS/osx?
I should be able to export it to file afterwards, so an animation of images displayed on my app would not be enough.
Thanks!
Image I/O has the functionalities you need. Try this:
var images = ... // init your array of NSImage
let destinationURL = NSURL(fileURLWithPath: "/path/to/image.gif")
let destinationGIF = CGImageDestinationCreateWithURL(destinationURL, kUTTypeGIF, images.count, nil)!
// The final size of your GIF. This is an optional parameter
var rect = NSMakeRect(0, 0, 350, 250)
// This dictionary controls the delay between frames
// If you don't specify this, CGImage will apply a default delay
let properties = [
(kCGImagePropertyGIFDictionary as String): [(kCGImagePropertyGIFDelayTime as String): 1.0/16.0]
]
for img in images {
// Convert an NSImage to CGImage, fitting within the specified rect
// You can replace `&rect` with nil
let cgImage = img.CGImageForProposedRect(&rect, context: nil, hints: nil)!
// Add the frame to the GIF image
// You can replace `properties` with nil
CGImageDestinationAddImage(destinationGIF, cgImage, properties)
}
// Write the GIF file to disk
CGImageDestinationFinalize(destinationGIF)

Swift playground - cannot convert a filtered UIImage to a CGImage

In a Swift playground, I am loading a JPEG, converting it to a UIImage and filtering it to monochrome.
I then convert the resulting filtered image to a UIImage.
The input and the filtered images display correctly.
I then convert both images to a CGImage type.
This works for the input image, but the filtered image returns nil from the conversion:
// Get an input image
let imageFilename = "yosemite.jpg"
let inputImage = UIImage(named: imageFilename )
let inputCIImage = CIImage(image:inputImage!)
// Filter the input image - make it monochrome
let filter = CIFilter(name: "CIPhotoEffectMono")
filter!.setDefaults()
filter!.setValue(inputCIImage, forKey: kCIInputImageKey)
let CIout = filter!.outputImage
let filteredImage = UIImage(CIImage: CIout!)
// Convert the input image to a CGImage
let inputCGImageRef = inputImage!.CGImage // Result: <CGImage 0x7fdd095023d0>
// THE LINE ABOVE WORKS
// Try to convert the filtered image to a CGImage
let filteredCGImageRef = filteredImage.CGImage // Result: nil
// THE LINE ABOVE DOES NOT WORK
// Note that the compiler objects to 'filteredImage!.CGImage'
What's wrong?
A UIImage created from a CIImage as you've done isn't backed by a CGImage. You need to explicitly create one:
let context = CIContext()
let filteredCGImageRef = context.createCGImage(
CIout!,
fromRect: CIout!.extent)
If you need a UIImage, create that from the CGImage rendered by the CIContext:
UIImage(CGImage: filteredCGImageRef)
Cheers,
Simon

Apply CiFilter GaussianBlur

As the title says I need to implement GaussianBlur to an UIImage; i tried to search for a tutorial but I am not still able to implement it. I tried this
var imageToBlur = CIImage(image: coro.logo)
var blurfilter = CIFilter(name: "CIGaussianBlur")
blurfilter.setValue(imageToBlur, forKey: "inputImage")
blurfilter.setValue(2, forKey: "inputImage")
var resultImage = blurfilter.valueForKey("outputImage") as! CIImage
var blurredImage = UIImage(CIImage: resultImage)
self.immagineCoro.image = blurredImage
importing CoreImage framework, but Xcode shows me an error ("NSInvalidArgumentException") at line 5. Can anyone help me to implement gaussianBlur and CIFilter in general?
Edit: thank to you both, but I have an other question; I need to apply blur only to a little part of the image like this
I just tried your code, and here's the modification I suggest, this works:
let fileURL = NSBundle.mainBundle().URLForResource("th", withExtension: "png")
let beginImage = CIImage(contentsOfURL: fileURL)
var blurfilter = CIFilter(name: "CIGaussianBlur")
blurfilter.setValue(beginImage, forKey: "inputImage")
//blurfilter.setValue(2, forKey: "inputImage")
var resultImage = blurfilter.valueForKey("outputImage") as! CIImage
var blurredImage = UIImage(CIImage: resultImage)
self.profileImageView.image = blurredImage
So, commenting out the portion you see above, did the trick and I get a blurred image as expected. And I'm using the file path, but this shouldn't make a difference from what you have.
You've used inputImage twice. The second time is probably meant to be inputRadius.
You might want to create a CIImage greyscale mask image with the shape you want, a blurred CIImage (using CIGaussianBlur), and then use CIBlendWithMask to blend them together.
The inputs of CIBlendWithMask are the input image (the blurred image), the input background image (the unblurred image), and the mask image (the shape you want). The output is the image you desire.

UIImagePNGRepresentation(UIImage()) returns nil

Why does UIImagePNGRepresentation(UIImage()) returns nil?
I'm trying to create a UIImage() in my test code just to assert that it was correctly passed around.
My comparison method for two UIImage's uses the UIImagePNGRepresentation(), but for some reason, it is returning nil.
Thank you.
UIImagePNGRepresentation() will return nil if the UIImage provided does not contain any data. From the UIKit Documentation:
Return Value
A data object containing the PNG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
When you initialize a UIImage by simply using UIImage(), it creates a UIImage with no data. Although the image isn't nil, it still has no data. And, because the image has no data, UIImagePNGRepresentation() just returns nil.
To fix this, you would have to use UIImage with data. For example:
var imageName: String = "MyImageName.png"
var image = UIImage(named: imageName)
var rep = UIImagePNGRepresentation(image)
Where imageName is the name of your image, included in your application.
In order to use UIImagePNGRepresentation(image), image must not be nil, and it must also have data.
If you want to check if they have any data, you could use:
if(image == nil || image == UIImage()){
//image is nil, or has no data
}
else{
//image has data
}
The UIImage documentation says
Image objects are immutable, so you cannot change their properties after creation. This means that you generally specify an image’s properties at initialization time or rely on the image’s metadata to provide the property value.
Since you've created the UIImage without providing any image data, the object you've created has no meaning as an image. UIKit and Core Graphics don't appear to allow 0x0 images.
The simplest fix is to create a 1x1 image instead:
UIGraphicsBeginImageContext(CGSizeMake(1, 1))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
I faced the same issue i was converting UIImage to pngData but sometime it returns nil. i fixed it by just creating copy of image
func getImagePngData(img : UIImage) -> Data {
let pngData = Data()
if let hasData = img.pngData(){
print(hasData)
pngData = hasData
}
else{
UIGraphicsBeginImageContext(img.size)
img.draw(in: CGRect(x: 0.0, y: 0.0, width: img.width,
height: img.height))
let resultImage =
UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print(resultImage.pngData)
pngData = resultImage.pngData
}
return pngData
}