2

I'm trying to convert SKSpriteNode as a PNG image with transparency to Camera Roll.

This saves the image but not with transparency:

let image = UIImage(cgImage: (spriteNode.texture?.cgImage())!)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

This complains:

Cannot convert value of type 'Data?' to expected argument type 'UIImage'

let image = UIImage(cgImage: (createdCloudShadow.texture?.cgImage())!)
let image2 = UIImagePNGRepresentation(image)
UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil)

How can I save SKSpriteNode as PNG to camera Roll?

user594883
  • 1,261
  • 2
  • 14
  • 34

2 Answers2

3

The UIImagePNGRepresentation(_:) function returns Data? as can be seen from the documentation.

So you probably just need to rewrite as follows:

let image = UIImage(cgImage: (createdCloudShadow.texture?.cgImage())!)
let imData = UIImagePNGRepresentation(image)
let image2 = UIImage(data: imData)
UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil)
Pranav Kasetti
  • 4,773
  • 2
  • 16
  • 38
1

This is in addition to @PranavKasetti answer.

In Swift 4.2, if you want to save a SKTexture to a file in your Mac (and maybe add the file to your project) here is a quick solution:

func saveTexture(){

    print("Saving Texture to Mac Desktop")

    let noiseMap = scene!.noiseMap! // Reference to the node you want to save
    let noiseTexture = SKTexture(noiseMap: noiseMap)
    let cgNoise = noiseTexture.cgImage()

    let imageRep = NSBitmapImageRep(cgImage: cgNoise)
    let imData = imageRep.representation(using: .png, properties: [:])

    let fileManager = FileManager.default
    let urls = fileManager.urls(for: .desktopDirectory, in: .userDomainMask).first!

    if let theData = imData{
        do{
            try theData.write(to: urls.appendingPathComponent("SavedNoise.png"))
        }catch{
            print("COULD NOT SAVE")
        }
    }
}
Farini
  • 883
  • 1
  • 18
  • 35