pcolton / potrace Goto Github PK
View Code? Open in Web Editor NEWTransform a bitmap into a smooth, scalable vector image.
License: GNU General Public License v2.0
Transform a bitmap into a smooth, scalable vector image.
License: GNU General Public License v2.0
I compare with an edition that wrote with c#,and found that this swift edition is more slower when produce a pic of dim 500*500. Even though c# and swift use the same algorithm and their difference is only the grammar. I am so confused.
I built a SwiftUi version, but the app crashed on this func. Any clue why? : )
init(data: UnsafeMutableRawPointer, width: Int, height: Int) {
let pixelData = data.assumingMemoryBound(to: UInt8.self)
bm = Bitmap(width: width, height: height)
var j = 0, i = 0
for _ in 0..<bm.data.count {
let val = 0.2126 * Double(pixelData[i]) + 0.7153 * Double(pixelData[i + 1]) +
0.0721 * Double(pixelData[i + 2])
bm.data[j] = val < 128 ? 1 : 0
i += 4
j += 1
}
}
Thread 2: EXC_BAD_ACCESS (code=1, address=0x10ac28848)
import SwiftUI
struct ContentView: View {
@State private var turdSize: Int = 2
@State private var curveTolerance: Float = 1.0
@State private var optCurve: Bool = true
@State private var originalImage: UIImage? = UIImage(named: "elephant")
@State private var curvesImage: UIImage?
// ... other state properties ...
// MARK: - Body
var body: some View {
VStack {
if let originalImage = originalImage {
Image(uiImage: originalImage)
.resizable()
.aspectRatio(contentMode: .fit)
}
if let curvesImage = curvesImage {
Image(uiImage: curvesImage)
.resizable()
.aspectRatio(contentMode: .fit)
}
Text("Curve Tolerance (\(curveTolerance))")
Slider(value: $curveTolerance, in: 0...10, step: 0.1)
.disabled(!optCurve)
.onChange(of: curveTolerance) { newValue in
updateImage()
}
Text("Turd Size (\(turdSize))")
Slider(value: Binding(
get: { Float(turdSize) },
set: { turdSize = Int($0) }
), in: 0...100)
.onChange(of: turdSize) { newValue in
updateImage()
}
Toggle("Optimize Curve", isOn: $optCurve)
.onChange(of: optCurve) { newValue in
updateImage()
}
}
.onAppear {
updateImage()
}
}
// MARK: - Methods
func updateImage() {
guard let originalImage = originalImage,
var pixelData = originalImage.pixelData() else {
print("Could not get pixel data from the image.")
return
}
// Assuming `Potrace` is your image processing object and `Settings` is the configuration
var settings = Potrace.Settings()
settings.turdsize = turdSize
settings.optcurve = optCurve
settings.opttolerance = Double(curveTolerance)
// Process the image pixels with Potrace
let width = Int(originalImage.size.width)
let height = Int(originalImage.size.height)
// Pass the array of UInt8 to the Potrace initializer
pixelData.withUnsafeMutableBytes { rawBufferPointer in
guard let rawPointer = rawBufferPointer.baseAddress else {
print("Unable to get raw pointer to pixel data.")
return
}
DispatchQueue.global(qos: .userInitiated).async {
let potrace = Potrace(data: rawPointer, width: width, height: height)
potrace.process(settings: settings)
// Assuming we get a bezier path back to convert to UIImage
let bezierPath = potrace.getBezierPath(scale: 2.0)
let newImage = self.imageFromBezierPath(path: bezierPath, size: CGSize(width: width, height: height))
DispatchQueue.main.async {
// Update the curvesImage on the main thread since it's a UI update
self.curvesImage = newImage
}
}
}
}
private func imageFromBezierPath(path: UIBezierPath, size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
if let context = UIGraphicsGetCurrentContext() {
UIColor.black.set()
context.addPath(path.cgPath)
context.fillPath()
let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return image
}
return UIImage()
}
}
extension UIImage {
func pixelData() -> [UInt8]? {
let size = self.size
let dataSize = size.width * size.height * 4
var pixelData = [UInt8](repeating: 0, count: Int(dataSize))
let colorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(data: &pixelData,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: 8,
bytesPerRow: 4 * Int(size.width),
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
guard let cgImage = self.cgImage else { return nil }
context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
return pixelData
}
}
// Preview provider
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.