programing

IOS의 UIView에서 이미지를 응용 프로그램 문서 폴더에 저장

codeshow 2023. 10. 19. 22:53
반응형

IOS의 UIView에서 이미지를 응용 프로그램 문서 폴더에 저장

사용자가 이미지를 저장할 때까지 이미지를 배치하고 유지할 수 있는 UImageView가 있습니다.문제는 보기에 저장한 이미지를 실제로 저장하고 검색하는 방법을 알 수 없다는 것입니다.

다음과 같이 이미지를 검색하여 UImageView에 배치했습니다.

//Get Image 
- (void) getPicture:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = (sender == myPic) ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentModalViewController:picker animated:YES];
    [picker release];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage (UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    myPic.image = image;
    [picker dismissModalViewControllerAnimated:YES];
}

선택한 이미지를 내 UImageView에 잘 표시하는데 저장하는 방법을 모르겠어요.보기의 다른 모든 부분(대부분 UIT 텍스트 필드)을 Core Data에 저장하고 있습니다.검색하고 검색하고 사람들이 제안한 많은 코드 조각을 시도했지만 코드를 제대로 입력하지 않거나 코드를 설정한 방식으로 이러한 제안이 작동하지 않습니다.전자일 가능성이 높습니다.UImageView에서 텍스트를 UItextFields에 저장할 때 사용하는 것과 동일한 작업(저장 버튼)을 사용하여 이미지를 UImageView에 저장하고자 합니다.UITextField 정보를 저장하는 방법은 다음과 같습니다.

// Handle Save Button
- (void)save {

    // Get Info From UI
    [self.referringObject setValue:self.myInfo.text forKey:@"myInfo"];

앞서 말씀드린 것처럼, 이를 해결하기 위해 몇 가지 방법을 시도해 보았지만, 파악이 되지 않습니다.난생 처음으로 무생물에 신체적 해를 끼치고 싶었지만, 겨우 자제할 수 있었습니다.

사용자가 배치한 이미지를 응용 프로그램의 문서 폴더에 있는 UIImageView에 저장한 다음 사용자가 해당 보기를 스택에 밀어 넣을 때 다른 UIImageView에 저장할 수 있습니다.어떤 도움이라도 주시면 대단히 감사하겠습니다!

다 괜찮아, 임마.자신이나 다른 사람에게 피해를 주지 마세요.

데이터 세트가 너무 커지면 성능에 영향을 미칠 수 있기 때문에 이러한 이미지를 코어 데이터에 저장하고 싶지 않을 수도 있습니다.이미지를 파일에 쓰는 것이 좋습니다.

NSData *pngData = UIImagePNGRepresentation(image);

이것은 당신이 촬영한 이미지의 PNG 데이터를 끌어냅니다.여기서 파일에 쓸 수 있습니다.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory 
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file

나중에 읽는 것도 같은 방식으로 작동합니다.위에서 한 것처럼 경로를 구축한 다음:

NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];

코드가 사방에 널려 있는 것을 원하지 않기 때문에, 당신은 아마도 당신을 위해 경로 문자열을 만드는 방법을 만드는 것을 원할 것입니다.다음과 같이 보일 수 있습니다.

- (NSString *)documentsPathForFileName:(NSString *)name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);  
    NSString *documentsPath = [paths objectAtIndex:0];

    return [documentsPath stringByAppendingPathComponent:name]; 
}

도움이 되길 바랍니다.

스위프트 3.0 버전

let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
        
let img = UIImage(named: "1.jpg")!// Or use whatever way to get the UIImage object
let imgPath = URL(fileURLWithPath: documentDirectoryPath.appendingPathComponent("1.jpg"))// Change extension if you want to save as PNG

do{
    try UIImageJPEGRepresentation(img, 1.0)?.write(to: imgPath, options: .atomic)//Use UIImagePNGRepresentation if you want to save as PNG
}catch let error{
    print(error.localizedDescription)
}

스위프트 4(확장 포함)

extension UIImage{

func saveImage(inDir:FileManager.SearchPathDirectory,name:String){
    guard let documentDirectoryPath = FileManager.default.urls(for: inDir, in: .userDomainMask).first else {
        return
    }
    let img = UIImage(named: "\(name).jpg")!

    // Change extension if you want to save as PNG.
    let imgPath = URL(fileURLWithPath: documentDirectoryPath.appendingPathComponent("\(name).jpg").absoluteString)
    do {
        try UIImageJPEGRepresentation(img, 0.5)?.write(to: imgPath, options: .atomic)
    } catch {
        print(error.localizedDescription)
    }
  }
}

사용예시

 image.saveImage(inDir: .documentDirectory, name: "pic")

이것은 Swift 4.2에 대한 Fangming Ning의 답변으로, 문서 디렉토리 경로를 검색하기 위해 권장되고 더 많은 Swifty 방법과 더 나은 문서로 업데이트되었습니다.새로운 방법에 대한 Fangming Ning의 공로도 인정합니다.

guard let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
    return
}

//Using force unwrapping here because we're sure "1.jpg" exists. Remember, this is just an example.
let img = UIImage(named: "1.jpg")!

// Change extension if you want to save as PNG.
let imgPath = documentDirectoryPath.appendingPathComponent("1.jpg")

do {
    //Use .pngData() if you want to save as PNG.
    //.atomic is just an example here, check out other writing options as well. (see the link under this example)
    //(atomic writes data to a temporary file first and sending that file to its final destination)
    try img.jpegData(compressionQuality: 1)?.write(to: imgPath, options: .atomic)
} catch {
    print(error.localizedDescription)
}

여기서 가능한 모든 데이터 쓰기 옵션을 확인해 보십시오.

#pragma mark - Save Image To Local Directory

- (void)saveImageToDocumentDirectoryWithImage:(UIImage *)capturedImage {
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/images"];
    
    //Create a folder inside Document Directory
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

    NSString *imageName = [NSString stringWithFormat:@"%@/img_%@.png", dataPath, [self getRandomNumber]] ;
    // save the file
    if ([[NSFileManager defaultManager] fileExistsAtPath:imageName]) {
        // delete if exist
        [[NSFileManager defaultManager] removeItemAtPath:imageName error:nil];
    }
    
    NSData *imageDate = [NSData dataWithData:UIImagePNGRepresentation(capturedImage)];
    [imageDate writeToFile: imageName atomically: YES];
}


#pragma mark - Generate Random Number

- (NSString *)getRandomNumber {
    NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); // returned as a double
    long digits = (long)time; // this is the first 10 digits
    int decimalDigits = (int)(fmod(time, 1) * 1000); // this will get the 3 missing digits
    //long timestamp = (digits * 1000) + decimalDigits;
    NSString *timestampString = [NSString stringWithFormat:@"%ld%d",digits ,decimalDigits];
    return timestampString;
}

스위프트에서:

let paths: [NSString?] = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .LocalDomainMask, true)
if let path = paths[0]?.stringByAppendingPathComponent(imageName) {
    do {
        try UIImagePNGRepresentation(image)?.writeToFile(path, options: .DataWritingAtomic)
    } catch {
        return
    }
}

언급URL : https://stackoverflow.com/questions/6821517/save-an-image-to-application-documents-folder-from-uiview-on-ios

반응형