簡體   English   中英

如何將UIImage保存到文件?

[英]How do I save a UIImage to a file?

如果我有一個來自imagePicker的UIImage ,我該如何將它保存到文檔目錄中的子文件夾?

當然,您可以在應用的文檔文件夾中創建子文件夾。 您使用NSFileManager來執行此操作。

您使用UIImagePNGRepresentation將您的圖像轉換為NSData並將其保存到磁盤。

// Create path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

核心數據與將圖像保存到磁盤無關。

在Swift 3中:

// Create path.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/MyImageName.png"

// Save image.
UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)

您必須將圖像的表示形式構造為特定格式 (例如,JPEG或PNG),然后在表示上調用writeToFile:atomically: on:

UIImage *image = ...;
NSString  *path = ...;
[UIImageJPEGRepresentation(image, 1.0) writeToFile:path atomically:YES];

以上內容很有用,但它們沒有回答您如何保存在子目錄中或從UIImagePicker獲取圖像的問題。

首先,您必須指定控制器在.m或.h代碼文件中實現圖像選擇器的委托,例如:

@interface CameraViewController () <UIImagePickerControllerDelegate>

@end

然后你實現委托的imagePickerController:didFinishPickingMediaWithInfo:方法,你可以從圖像選擇器中獲取照片並保存它(當然,你可能有另一個處理保存的類/對象,但我只是顯示代碼在方法內):

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // get the captured image
    UIImage *image = (UIImage *)info[UIImagePickerControllerOriginalImage];


    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *imageSubdirectory = [documentsDirectory stringByAppendingPathComponent:@"MySubfolderName"];

    NSString *filePath = [imageSubdirectory stringByAppendingPathComponent:@"MyImageName.png"];

    // Convert UIImage object into NSData (a wrapper for a stream of bytes) formatted according to PNG spec
    NSData *imageData = UIImagePNGRepresentation(image); 
    [imageData writeToFile:filePath atomically:YES];
}

如果要保存為JPEG圖像,最后3行將是:

NSString *filePath = [imageSubdirectory stringByAppendingPathComponent:@"MyImageName.jpg"];

// Convert UIImage object into NSData (a wrapper for a stream of bytes) formatted according to JPG spec
NSData *imageData = UIImageJPEGRepresentation(image, 0.85f); // quality level 85%
[imageData writeToFile:filePath atomically:YES];
extension UIImage {
    /// Save PNG in the Documents directory
    func save(_ name: String) {
        let path: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let url = URL(fileURLWithPath: path).appendingPathComponent(name)
        try! UIImagePNGRepresentation(self)?.write(to: url)
        print("saved image at \(url)")
    }
}

// Usage: Saves file in the Documents directory
image.save("climate_model_2017.png")
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:path atomically:YES];

其中path是您要將其寫入的文件的名稱。

首先,您應該獲取Documents目錄

/* create path to cache directory inside the application's Documents directory */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"fileName"];

然后你應該將照片保存到文件中

NSData *photoData = UIImageJPEGRepresentation(photoImage, 1);
[photoData writeToFile:filePath atomically:YES];

在Swift 4.2中:

// Create path.
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if let filePath = paths.first?.appendingPathComponent("MyImageName.png") {
    // Save image.
    do {
       try image.pngData()?.write(to: filePath, options: .atomic)
    } catch {
       // Handle the error
    }
}

在Swift 4中:

// Create path.
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if let filePath = paths.first?.appendingPathComponent("MyImageName.png") {
    // Save image.
    do {
       try UIImagePNGRepresentation(image)?.write(to: filePath, options: .atomic)
    }
    catch {
       // Handle the error
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM