Skip to content

Commit c86efef

Browse files
committed
process on thread
1 parent 14d1653 commit c86efef

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

Sources/iOSIntPackage/ImageProcessor.swift

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import UIKit
1111

1212
public struct ImageProcessor {
1313

14+
// MARK: - Interface
15+
1416
public init() {}
1517

1618
// применение фильтра к изображению в главном потоке, не требует явного вызова DispatchQueue.main при работе с UI
@@ -37,6 +39,26 @@ public struct ImageProcessor {
3739
handler: completion)
3840
}
3941

42+
// MARK: - Internal interface
43+
44+
public func processImagesOnThread(
45+
sourceImages: [UIImage],
46+
filter: ColorFilter,
47+
qos: QualityOfService,
48+
completion: @escaping ([CGImage?]) -> Void
49+
) {
50+
let thread = ImageThread(qos: qos) {
51+
applyFilterOnThread(
52+
sourceImages: sourceImages,
53+
filter: filter,
54+
completion: completion
55+
)
56+
}
57+
thread.start()
58+
}
59+
60+
// MARK: - Private func
61+
4062
private func applyFilter(
4163
filter: ColorFilter,
4264
image: UIImage,
@@ -84,4 +106,30 @@ public struct ImageProcessor {
84106
handler(outputImage)
85107
}
86108
}
109+
110+
private func applyFilterOnThread(
111+
sourceImages: [UIImage],
112+
filter: ColorFilter,
113+
completion: @escaping ([CGImage?]) -> Void
114+
) {
115+
let context = CIContext()
116+
let output = sourceImages.map { image -> CGImage in
117+
guard let source = CIImage(image: image) else { fatalError("Error creating source image") }
118+
var params = filter.parameters
119+
params[ColorFilter.imageKey] = source
120+
guard let filter = CIFilter(
121+
name: filter.filterName,
122+
parameters: params
123+
) else { fatalError("Error creating filter") }
124+
125+
guard let filteredImage = filter.outputImage else { fatalError("Error filtering image") }
126+
127+
guard let outputImage = context.createCGImage(
128+
filteredImage,
129+
from: filteredImage.extent
130+
) else { fatalError("Error creating output image") }
131+
return outputImage
132+
}
133+
completion(output)
134+
}
87135
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
//
2+
// ImageThread.swift
3+
//
4+
//
5+
// Created by Maxim Abakumov on 2021. 06. 17.
6+
//
7+
// Copyright © 2020, Maxim Abakumov. MIT License.
8+
//
9+
10+
import Foundation
11+
12+
class ImageThread: Thread {
13+
14+
private var workItem: () -> Void
15+
16+
init(
17+
qos: QualityOfService,
18+
workItem: @escaping () -> Void
19+
) {
20+
self.workItem = workItem
21+
super.init()
22+
super.qualityOfService = qos
23+
}
24+
}

0 commit comments

Comments
 (0)