我想对JPEG图像进行矩形裁剪。我有以下代码将创建重复的图像。它使用一个NSImage。我不知道如何创建裁剪的图像。
func crop(index: Int) {
let croppedImageUrl = ...
let imageUrl = ...
// Create a cropped image.
let data = try? Data(contentsOf: imageUrl)
let image = NSImage(data: data!)
let tiffRepresentation = (image?.tiffRepresentation)!
let bitmap = NSBitmapImageRep(data: tiffRepresentation)
let representation = bitmap?.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])
do {
try representation?.write(to: croppedImageUrl, options: [.withoutOverwriting])
} catch let error as NSError {
print(error.localizedDescription)
}
}
答案 0 :(得分:0)
这可以帮助您裁剪图像
func crop() -> UIImage? {
let imageUrl = URL(string: "imageUrl")!
let data = try! Data(contentsOf: imageUrl)
let image = UIImage(data: data)!
// Crop rectangle
let width = min(image.size.width, image.size.height)
let size = CGSize(width: width, height: width)
// If you want to crop center of image
let startPoint = CGPoint(x: (image.size.width - width) / 2, y: (image.size.height - width) / 2)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
image.draw(in: CGRect(origin: startPoint, size: size))
let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return croppedImage
}
答案 1 :(得分:0)
类似...
func crop(nsImage: NSImage,rect: CGRect) -> NSImage {
let cgImage = (nsImage?.cgImage(forProposedRect: nil, context: nil, hints: nil)?.cropping(to: rect))!
let size = NSSize(width: rect.width, height: rect.height)
return NSImage(cgImage: cgImage, size: size)
}
抱歉,未编译此代码片段,但通用方法在我的代码中起作用。如果可能的话,做为NSImage的扩展可能做得更好。