아이폰 사진 보관함에 사진을 저장하는 방법?
내 프로그램에서 생성 한 이미지를 카메라에서 (아마도 카메라에서 아닐 수도 있음) iPhone의 시스템 사진 라이브러리에 저장하려면 어떻게해야합니까?
이 기능을 사용할 수 있습니다 :
UIImageWriteToSavedPhotosAlbum(UIImage *image,
id completionTarget,
SEL completionSelector,
void *contextInfo);
저장이 완료 되면 알림을 받으려면 completionTarget , completionSelector 및 contextInfo 만 필요합니다 . UIImage
그렇지 않으면을 전달할 수 있습니다 nil
.
에 대한 공식 문서를UIImageWriteToSavedPhotosAlbum()
참조하십시오 .
iOS 9.0에서 사용되지 않습니다.
iOS 4.0 + AssetsLibrary 프레임 워크를 사용하여 UIImageWriteToSavedPhotosAlbum 방법보다 훨씬 빠릅니다.
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
// TODO: error handling
} else {
// TODO: success handling
}
}];
[library release];
가장 간단한 방법은 다음과 같습니다.
UIImageWriteToSavedPhotosAlbum(myUIImage, nil, nil, nil);
의 경우 swift를 사용하여 iOS 사진 라이브러리Swift
에 저장을 참조하십시오.
기억해야 할 사항 : 콜백을 사용하는 경우 선택기가 다음 형식을 준수하는지 확인하십시오.
- (void) image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo;
그렇지 않으면 다음과 같은 오류가 발생합니다.
[NSInvocation setArgument:atIndex:]: index (2) out of bounds [-1, 1]
배열에서 이미지를 이렇게 전달하십시오.
-(void) saveMePlease {
//Loop through the array here
for (int i=0:i<[arrayOfPhotos count]:i++){
NSString *file = [arrayOfPhotos objectAtIndex:i];
NSString *path = [get the path of the image like you would in DOCS FOLDER or whatever];
NSString *imagePath = [path stringByAppendingString:file];
UIImage *image = [[[UIImage alloc] initWithContentsOfFile:imagePath]autorelease];
//Now it will do this for each photo in the array
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}
오타가 미안해서 방금이 작업을 수행했지만 요점을 알 수 있습니다.
사진 배열을 저장할 때 for 루프를 사용하지 말고 다음을 수행하십시오.
-(void)saveToAlbum{
[self performSelectorInBackground:@selector(startSavingToAlbum) withObject:nil];
}
-(void)startSavingToAlbum{
currentSavingIndex = 0;
UIImage* img = arrayOfPhoto[currentSavingIndex];//get your image
UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{ //can also handle error message as well
currentSavingIndex ++;
if (currentSavingIndex >= arrayOfPhoto.count) {
return; //notify the user it's done.
}
else
{
UIImage* img = arrayOfPhoto[currentSavingIndex];
UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
}
에서 스위프트 :
// Save it to the camera roll / saved photo album
// UIImageWriteToSavedPhotosAlbum(self.myUIImageView.image, nil, nil, nil) or
UIImageWriteToSavedPhotosAlbum(self.myUIImageView.image, self, "image:didFinishSavingWithError:contextInfo:", nil)
func image(image: UIImage!, didFinishSavingWithError error: NSError!, contextInfo: AnyObject!) {
if (error != nil) {
// Something wrong happened.
} else {
// Everything is alright.
}
}
아래 기능이 작동합니다. 여기에서 복사하여 붙여 넣을 수 있습니다 ...
-(void)savePhotoToAlbum:(UIImage*)imageToSave {
CGImageRef imageRef = imageToSave.CGImage;
NSDictionary *metadata = [NSDictionary new]; // you can add
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:imageRef metadata:metadata completionBlock:^(NSURL *assetURL,NSError *error){
if(error) {
NSLog(@"Image save eror");
}
}];
}
homeDirectoryPath = NSHomeDirectory();
unexpandedPath = [homeDirectoryPath stringByAppendingString:@"/Pictures/"];
folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];
unexpandedImagePath = [folderPath stringByAppendingString:@"/image.png"];
imagePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL]) {
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath attributes:nil];
}
내 마지막 답변은 ..
저장하려는 각 이미지에 대해 NSMutableArray에 추가하십시오.
//in the .h file put:
NSMutableArray *myPhotoArray;
///then in the .m
- (void) viewDidLoad {
myPhotoArray = [[NSMutableArray alloc]init];
}
//However Your getting images
- (void) someOtherMethod {
UIImage *someImage = [your prefered method of using this];
[myPhotoArray addObject:someImage];
}
-(void) saveMePlease {
//Loop through the array here
for (int i=0:i<[myPhotoArray count]:i++){
NSString *file = [myPhotoArray objectAtIndex:i];
NSString *path = [get the path of the image like you would in DOCS FOLDER or whatever];
NSString *imagePath = [path stringByAppendingString:file];
UIImage *image = [[[UIImage alloc] initWithContentsOfFile:imagePath]autorelease];
//Now it will do this for each photo in the array
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}
위의 답변 중 일부를 기반으로 UIImageView 범주를 만들었습니다.
헤더 파일 :
@interface UIImageView (SaveImage) <UIActionSheetDelegate>
- (void)addHoldToSave;
@end
이행
@implementation UIImageView (SaveImage)
- (void)addHoldToSave{
UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
longPress.minimumPressDuration = 1.0f;
[self addGestureRecognizer:longPress];
}
- (void)handleLongPress:(UILongPressGestureRecognizer*)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
UIActionSheet* _attachmentMenuSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:@"Save Image", nil];
[_attachmentMenuSheet showInView:[[UIView alloc] initWithFrame:self.frame]];
}
else if (sender.state == UIGestureRecognizerStateBegan){
//Do nothing
}
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
UIImageWriteToSavedPhotosAlbum(self.image, nil,nil, nil);
}
}
@end
이제 이미지 뷰에서이 함수를 호출하면됩니다.
[self.imageView addHoldToSave];
선택적으로 minimumPressDuration 매개 변수를 변경할 수 있습니다.
에서 스위프트 2.2
UIImageWriteToSavedPhotosAlbum(image: UIImage, _ completionTarget: AnyObject?, _ completionSelector: Selector, _ contextInfo: UnsafeMutablePointer<Void>)
If you do not want to be notified when the image is done saving then you may pass nil in the completionTarget, completionSelector and contextInfo parameters.
Example:
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.imageSaved(_:didFinishSavingWithError:contextInfo:)), nil)
func imageSaved(image: UIImage!, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
if (error != nil) {
// Something wrong happened.
} else {
// Everything is alright.
}
}
The important thing to note here is that your method that observes the image saving should have these 3 parameters else you will run into NSInvocation errors.
Hope it helps.
Swift 4
func writeImage(image: UIImage) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.finishWriteImage), nil)
}
@objc private func finishWriteImage(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if (error != nil) {
// Something wrong happened.
print("error occurred: \(String(describing: error))")
} else {
// Everything is alright.
print("saved success!")
}
}
You can use this
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImageWriteToSavedPhotosAlbum(img.image, nil, nil, nil);
});
참고URL : https://stackoverflow.com/questions/178915/how-to-save-picture-to-iphone-photo-library
'IT' 카테고리의 다른 글
HTTP 오류 500.19 및 오류 코드 : 0x80070021 (0) | 2020.05.12 |
---|---|
서버 측 확장을 빌드하려면 postgresql-server-dev-XY를 설치하고 클라이언트 측 애플리케이션을 빌드하려면 libpq-dev를 설치해야합니다. (0) | 2020.05.12 |
matplotlib을 사용하여 두 개의 히스토그램을 동시에 플롯 (0) | 2020.05.12 |
div id에 자식이 있으면 jquery (0) | 2020.05.12 |
현재 내 애플리케이션을 실행중인 Android API 수준의 휴대 전화를 가져옵니다. (0) | 2020.05.12 |