หลังจากครั้งที่แล้วเมื่อได้รูปแล้วจะเป็นการบันทึก (Save) ไว้ใน photo album แต่ในบางกรณีเราไม่ต้องการบันทึกภาพลงในนั้น แต่ต้องการแค่บันทึกภาพเก็บไว้ และคราวหน้าอาจต้องเอามาใช้งานอีก โดยไม่จำเป็นต้องให้ user เข้าถึงรูปนั้นได้ เราจะบันทึกมันไว้ใน document directory นั่นเอง
จากเดิมหลังจากเลือกรูปเสร็จแล้วเราจะได้ image มาใช้ และเราเลือกที่จะบันทึกไว้ใน photo album ซึ่งหากต้องการเปลี่ยนมาเป็นการบันทึกลงไปใน document directory ก็ทำได้ดังนี้
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[UIImagePNGRepresentation(image) writeToFile:
[documentsDirectory stringByAppendingPathComponent: @"myImage.png"] atomically: YES];
ด้านบนเป็นการใช้ function ชื่อ UIImagePNGRepresentation() เพื่อเปลี่ยน image และจากนั้นเขียน image ลงไปตาม path ที่เรากำหนดไว้ ในที่นี้ก็คือใน document directory และกำหนดชื่อไฟล์เป็น myImage.png นั่นเอง
และเมื่อต้องการอ่านไฟล์ที่เราเขียนลงไปมาใช้งาน สามารถทำได้ดังนี้
if([[NSFileManager defaultManager] fileExistsAtPath: documentsDirectory]){
NSLog(@"found file");
uiImageView.image = [UIImage imageWithContentsOfFile: documentsDirectory];
}else{
NSLog(@"file not found");
}
เช่นเดิม ให้อ่านไฟล์ขึ้นมาจาก path ที่เราต้องการ และนำไปแสดงใน image view พร้อมใช้งานในโปรแกรมได้เลย
Related Link from Roti
จากเดิมหลังจากเลือกรูปเสร็จแล้วเราจะได้ image มาใช้ และเราเลือกที่จะบันทึกไว้ใน photo album ซึ่งหากต้องการเปลี่ยนมาเป็นการบันทึกลงไปใน document directory ก็ทำได้ดังนี้
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[UIImagePNGRepresentation(image) writeToFile:
[documentsDirectory stringByAppendingPathComponent: @"myImage.png"] atomically: YES];
ด้านบนเป็นการใช้ function ชื่อ UIImagePNGRepresentation() เพื่อเปลี่ยน image และจากนั้นเขียน image ลงไปตาม path ที่เรากำหนดไว้ ในที่นี้ก็คือใน document directory และกำหนดชื่อไฟล์เป็น myImage.png นั่นเอง
และเมื่อต้องการอ่านไฟล์ที่เราเขียนลงไปมาใช้งาน สามารถทำได้ดังนี้
NSLog(@"found file");
uiImageView.image = [UIImage imageWithContentsOfFile: documentsDirectory];
}else{
NSLog(@"file not found");
}
เช่นเดิม ให้อ่านไฟล์ขึ้นมาจาก path ที่เราต้องการ และนำไปแสดงใน image view พร้อมใช้งานในโปรแกรมได้เลย
Related Link from Roti