Ethan Hansen
Ethan Hansen

Reputation: 69

Splitting an image into a grid in Swift

I am attempting to split an image into 10'000 smaller ones, by dividing the image into a grid of 100x100. When I run the code, I receive an Error_Bad_Instruction.

import Cocoa
import CoreImage

public class Image {
public var image: CGImage?

     public func divide() -> [CGImage] {
        var tiles: [CGImage] = []
        for x in 0...100 {
            for y in 0...100 {

                let tile = image?.cropping(to: CGRect(x: (image?.width)!/x, y: (image?.height)!/y, width: (image?.width)! / 100, height: (image?.height)! / 100 ))
                tiles.append(tile!)

            }
        }
        return tiles
    }

    public init(image: CGImage) {
        self.image = image
    }
}

var img = Image(image: (NSImage(named: "aus-regions.jpg")?.cgImage(forProposedRect: nil, context: nil, hints: nil))!)
var a = img.divide()

Upvotes: 1

Views: 1241

Answers (1)

Laura Calinoiu
Laura Calinoiu

Reputation: 714

There are some problems with the code that you posted:

  1. forced wrapping the image
  2. loops go including 100 - you just need 99. Or as a comment suggests: for x in 0..<100
  3. you divide by 0 - in the first step
  4. your algorithm, is not forming a grid.

I've updated to obtain a grid, using an image that I had on my computer, and with widths and heights just of 10, because it using 100 was too long.

import Cocoa
import CoreImage

let times = 10
public class Image {
    public var image: CGImage?

    public func divide() -> [CGImage] {
        var tiles: [CGImage] = []
        for x in 0..<times {
            for y in 0..<times {

                let tile = image?.cropping(to: CGRect(x: x * (image?.width)!/times, y: y * (image?.height)!/times, width: (image?.width)! / times, height: (image?.height)! / times ))
                tiles.append(tile!)

            }
        }
        return tiles
     }

     public init(image: CGImage) {
         self.image = image
     }
 }

 if let image = NSImage(named: "bg.jpg")?.cgImage(forProposedRect: nil,   context: nil, hints: nil) {
      var img = Image(image: image)
      var a = img.divide()
 }

Upvotes: 3

Related Questions