我有一個UIImage,我想用DPI元數據集將它保存到照片中。我知道UIImage是不可變的,所以我必須創建一個新的UIImage。我使用this answer作爲參考,在UIImage上創建一個快速擴展函數,該函數生成一個DPI集的新UIImage。我用UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
成功地將它保存到照片。我通過電子郵件發送這個對自己(設置爲「實際大小」),並在預覽中打開它,但DPI總是留給在72如何使用DPI設置創建UIImage?
這裏是我轉換的功能:我是那種
func imageWithDPI(dpi :Int) -> UIImage? {
guard let sourceImageData = UIImageJPEGRepresentation(self, 0.8) else {
print("Couldn't make PNG Respresentation of UIImage")
return nil
}
guard let source = CGImageSourceCreateWithData(sourceImageData, nil) else {
print("Couldn't create source with sourceImageData")
return nil
}
var metadata = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [String:AnyObject] ?? [String:AnyObject]()
metadata[kCGImagePropertyDPIWidth as String] = dpi
metadata[kCGImagePropertyDPIHeight as String] = dpi
var exifDictionary = metadata[kCGImagePropertyTIFFDictionary as String] as? [String:AnyObject] ?? [String:AnyObject]()
exifDictionary[kCGImagePropertyTIFFXResolution as String] = dpi
exifDictionary[kCGImagePropertyTIFFYResolution as String] = dpi
metadata[kCGImagePropertyTIFFDictionary as String] = exifDictionary
var jfifDictionary = metadata[kCGImagePropertyJFIFDictionary as String] as? [String:AnyObject] ?? [String:AnyObject]()
jfifDictionary[kCGImagePropertyJFIFXDensity as String] = dpi
jfifDictionary[kCGImagePropertyJFIFYDensity as String] = dpi
jfifDictionary[kCGImagePropertyJFIFVersion as String] = 1
metadata[kCGImagePropertyJFIFDictionary as String] = jfifDictionary
guard let uti = CGImageSourceGetType(source) else {
print("Couldn't get type from source")
return nil
}
let destinationImageData = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(destinationImageData, uti, 1, nil) else {
print("Couldn't create destination with destinationImageData")
return nil
}
CGImageDestinationAddImageFromSource(destination, source,0, metadata)
CGImageDestinationFinalize(destination)
return UIImage(data: destinationImageData)
}
在Core Graphics中我的深度,所以任何建議將不勝感激。
非常感謝提前。
明天我回去工作時,我會放棄這一點。該圖像將被手動導入到一個尊重DPI以供以後打印的程序中,因此將該步驟自動化意味着這不是一項手動任務。謝謝。 –
也許我很困惑,但如果我保存這個原始數據,我怎麼能夠加載到預覽或Photoshop來檢查DPI? –
你是對的。使用'CGImageDestinationCreateWithURL(...)',''CGImageDestinationAddImageFromSource(...)'和'CGImageDestinationFinalize(...)'我可以將圖像寫入磁盤並保持DPI!真的非常感謝你。 –