2012-10-18 21 views
1

顯然,使用CGImages,您可以將kCGImagePropertyPNGXPixelsPerMeter和kCGImagePropertyPNGYPixelsPerMeter屬性添加到圖像中,並將它們添加到png的pHYs塊中。但UIImageWriteToSavedPhotosAlbum不直接接受CGImage。iOS:從磁盤加載PNG,爲其添加PixelPerMeter屬性,並將其保存到相冊

我一直試圖加載圖像作爲UIImage,然後創建一個CGImage,添加屬性,然後從該數據創建一個新的UIImage,並將其保存到相冊。

的圖像獲取寫入到相冊,但沒有PPM設置。我可以在MacOS上的預覽應用程序或使用ImageMagick的identify進行驗證。

ObjC不是我的專長,所以這裏就是我從類似計算器的問題拼湊。

UIImage *uiImage = [UIImage imageWithContentsOfFile:path]; 

NSDictionary* properties = [NSDictionary dictionaryWithObjectsAndKeys: 
          [NSDictionary dictionaryWithObjectsAndKeys: 
           [NSNumber numberWithInt:5905], (NSString *)kCGImagePropertyPNGXPixelsPerMeter, /* this doesn't work */ 
           [NSNumber numberWithInt:5905], (NSString *)kCGImagePropertyPNGYPixelsPerMeter, /* this doesn't work */ 
           @"This works when saved to disk.", (NSString *)kCGImagePropertyPNGDescription, 
           nil],(NSString*) kCGImagePropertyPNGDictionary, 
          nil]; 

NSMutableData* imageData = [NSMutableData data]; 
CGImageDestinationRef imageDest = CGImageDestinationCreateWithData((CFMutableDataRef) imageData, kUTTypePNG, 1, NULL); 

CGImageDestinationAddImage(imageDest, uiImage.CGImage, (CFDictionaryRef) properties); 
CGImageDestinationSetProperties(imageDest, (CFDictionaryRef) properties); /* I'm setting the properties twice because I was going crazy */ 
CGImageDestinationFinalize(imageDest); 

UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:imageData], nil, NULL, NULL); 

// This is a test to see if the data is getting stored at all. 
CGImageDestinationRef diskDest = CGImageDestinationCreateWithURL(
    (CFURLRef)[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@.dpi.png",path]], kUTTypePNG, 1, NULL); 

CGImageDestinationAddImage(diskDest, uiImage.CGImage, (CFDictionaryRef) properties); 
CGImageDestinationSetProperties(diskDest, (CFDictionaryRef) properties); 
CGImageDestinationFinalize(diskDest); 

更新:修改和簡化了一下代碼。仍將圖像保存到相冊和磁盤,但每米像素值不會保存。說明塊被保存到磁盤,但在寫入相冊時看起來會被剝離。

更新2:通過將文件保存爲jpeg並向其添加TIFF X/Y分辨率標記我已經能夠將保存到磁盤的版本存儲到72以外的PPI值。此信息仍被剝離在保存到相冊時關閉。

比較通過iOS相機應用拍攝的照片,通過Instagram拍攝的照片和通過我的代碼保存的照片,我注意到相機應用版本有大量的TIFF/EXIF標籤,而Instagram和我的相同有限的一組標籤。這讓我得出這樣的結論,即iOS故意去除這些標籤。一個明確的答案會幫助我在晚上睡覺。

+0

您是否試過將圖像拉回來檢查其屬性?也許該函數設置值,但沒有正確應用更改。你擁有的一切看起來都不錯。發生了大量的轉換,因此它可能是與不同​​對象類型的兼容性問題,並且無法真正設置屬性。我不能肯定地說,因爲自從我看到你的問題以來,我一直在看'CGImageDestination'。 – RileyE

+0

我只是嘗試使用CGImageDestinationCreateWithURL將圖像保存到磁盤,並且沒有設置PPM。所以,我如何應用這些屬性肯定有問題? – Calvin

回答

0

答案是不使用UIImageWriteToSavedPhotosAlbum。

有一個ALAssetsLibrary方法 [writeImageDataToSavedPhotosAlbum:元數據:completionBlock:]

元數據是在相同的格式作爲所述一個傳遞到CGImageDestinationSetProperties字典。 PNG和JFIF密度設置可能被破壞,我正在使用kCGImagePropertyTIFFXResolution。

相關問題