1

So I am using below code to fetch all the images from library which is working fine :

func grabPhotos(){

   let imgManager = PHImageManager.default()
   let requestOptions = PHImageRequestOptions()
   requestOptions.isSynchronous = true
   requestOptions.deliveryMode = .highQualityFormat
   let fetchOptions = PHFetchOptions()
   fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
   if let fetchResults : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions){

      if fetchResults.count>0{

       for i in 0..<fetchResults.count{

         imgManager.requestImage(for: fetchResults.object(at: i), targetSize: CGSize(width:100, height: 100), contentMode: .aspectFill, options: requestOptions, resultHandler: {

         image, error in
        self.Galleryimages.append(image!)

        print("array count is ",self.Galleryimages.count)
        self.photoCollectionview.reloadData()
      })
      }

    }
  }
}

I am showing all the images in my UICollectionView, but I didn't find any way to get original image whenever clicking on any thumbnail image. I want to fetch the original image (full size image) when user clicks on any thumbnail image which is populated in UICollectionView.

Thank you.

Sumeet Purohit
  • 657
  • 1
  • 7
  • 16
  • means what do you want to do ? – Jitendra Modi Feb 15 '17 at 09:41
  • Please see my edited question, I actually want to fetch the original size image when user click on any thumbnail image. – Sumeet Purohit Feb 15 '17 at 09:44
  • Aren't you storing all the images inside an array. What do you mean by not being able to get original image? – KrishnaCA Feb 15 '17 at 09:45
  • Actually you r getting all images from assets and displaying into collectioview then Those all r original images. Why do you say I am not getting original images ? – Jitendra Modi Feb 15 '17 at 09:46
  • @ KrishnaCA : using the code I mentioned, I am getting 100*100 size image which is used as thumbnail image but when user clicks on any image , I need to fetch the original size image. Here original images means images with original size. – Sumeet Purohit Feb 15 '17 at 09:46
  • @SumeetPurohit Check out my answer, sure it will help you – Jitendra Modi Feb 15 '17 at 10:55
  • @SumeetPurohit Now check my answer and also see my comment at last – Jitendra Modi Feb 15 '17 at 11:12
  • Possible duplicate of [How to get a low res image, or Thumbnail from the ALAssetRepresentation in Swift](http://stackoverflow.com/questions/32190423/how-to-get-a-low-res-image-or-thumbnail-from-the-alassetrepresentation-in-swift) – Stephen Rauch Feb 20 '17 at 01:19

2 Answers2

5

To load thumbnail image.

Got the solution after doing too much stuff, may be it can help to others. Below are the steps to do this.

Step 1 : Declare object of PHFetchResult

var Galleryimages: PHFetchResult<PHAsset>!

Step 2 : Fetch results from gallery using below code:

func grabPhotos(){

Galleryimages = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil)

}

Step 3 : Show the thumbnail images in your UI (collectionview/Tableview) using below code :

let imageview = cell.viewWithTag(1) as! UIImageView

PHImageManager.default().requestImage(for: (Galleryimages?[indexPath.row])!, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: nil) { (image: UIImage?, info: [AnyHashable: Any]?) -> Void in
  imageview.image = image
}

Step 4 : And finally get the full size image using below code.

let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.resizeMode = .exact

PHImageManager.default().requestImage(for: (Galleryimages[indexPath.row]), targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: options) { (image: UIImage?, info: [AnyHashable: Any]?) -> Void in
  if let image = image {
    //Use this originan image
  }
}
Hardik Thakkar
  • 15,269
  • 2
  • 94
  • 81
Sumeet Purohit
  • 657
  • 1
  • 7
  • 16
0

You are resizing images when U fetch from PHAsset. So use

targetsize : PHImageManagerMaximumSize

From this U can get original image with its original size. and for your collectionview you can direclty make thumbnail from it and display images. So when user taps on thumbnail, now you can show original image

Please use autoreleasepool for memory management.

for(PHAsset *asset in self.assets) {
    // This autorelease pool seems good (a1)
    autoreleasepool {
        NSLog(@"started requesting image %i", i);
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:[self imageRequestOptions] resultHandler:^(UIImage *image, NSDictionary *info) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //you can add autorelease pool here as well (a2)
                @autoreleasepool {
                    assetCount++;
                    NSError *error = [info objectForKey:PHImageErrorKey];
                    if (error) NSLog(@"Image request error: %@",error);
                    else {
                        NSString *imagePath = [appDelegate.docsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%i.png",i]];
                        NSData *imageData = UIImagePNGRepresentation(image);
                        if(imageData) {
                            [imageData writeToFile:imagePath atomically:YES];
                            [self.imagesArray addObject:imagePath];
                        }
                        else {
                            NSLog(@"Couldn't write image data to file.");
                        }
                        [self checkAddComplete];
                        NSLog(@"finished requesting image %i", i);
                    }
                } //a2 ends here
            });
        }];
        i++;
    } // a1 ends here
}
Jitendra Modi
  • 2,344
  • 12
  • 34
  • You're correct about using `PHImageManagerMaximumSize` as the parameter. However, it's not worth loading the full size image just for a thumbnail. You're better off requesting the full size image only when clicking on an image thumbnail and needing to display the full size image. – Abizern Feb 15 '17 at 09:59
  • @JeckyModi If I use PHImageManagerMaximumSize as targetsize, my app will crash because of memory pressure. That's I used 200 x 200 as target size to avoid the crash. Can you explain the complete way in your answer? – Sumeet Purohit Feb 15 '17 at 10:57
  • @SumeetPurohit you can use autoreleasepool as per in the answer http://stackoverflow.com/questions/33274791/high-memory-usage-looping-through-phassets-and-calling-requestimageforasset Please see the answer as you want – Jitendra Modi Feb 15 '17 at 11:01
  • @JeckyModi We are in ARC now so autoreleasepool won't be working now. – Sumeet Purohit Feb 15 '17 at 12:44
  • I got this line in swift autoreleasepool(invoking: <#T##() throws -> Result#>) – Jitendra Modi Feb 15 '17 at 12:53
  • https://github.com/apple/swift-evolution/blob/master/proposals/0061-autoreleasepool-signature.md – Jitendra Modi Feb 15 '17 at 12:56
  • @SumeetPurohit Just put this function, if it gives error at autoreleasepool then I will remove my answer. If not then accept my answer and upvote same. This is random function build by me. Sorry but its in objective c. – Jitendra Modi Feb 15 '17 at 13:02
  • @Jecky Modi: Used what exactly you said but Unfortunately, still app crashes due to memory pressure. – Sumeet Purohit Feb 16 '17 at 01:08