13

I want to create a Photos Library as existing photo library in iPhone. I add image in scrollviewer which is chosen from Photo library. Before add image i resize the selected image and set it to ImageView Control.But when i compare to added image quality with iPhone Photo library image quality, my control image is not good. How to bring the quality and withou memory overflow issue.

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a bitmap context.
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;

}
ageektrapped
  • 14,482
  • 7
  • 57
  • 72
Gnanavadivelu
  • 263
  • 4
  • 13

2 Answers2

22

I ran into this issue also. I think you're using an iPhone 4 with Retina Display. Even if you're not, you should account for it. Instead of UIGraphicsBeginImageContext(), use UIGraphicsBeginImageContextWithOptions() and use the scale property of UIScreen for the third argument. All iOS devices have the scale property, on iPhone 4 it's set to 2.0; on the rest, as I write this, it's set to 1.0.

So your code, with those changes, becomes

-(UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a bitmap context.
    UIGraphicsBeginImageContextWithOptions(newSize, YES, [UIScreen mainScreen].scale);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;

}
ageektrapped
  • 14,482
  • 7
  • 57
  • 72
  • 4
    Rather than using `[UIScreen mainScreen].scale` you can just use `image.scale`. – memmons Nov 14 '12 at 17:07
  • I read many articles and this simple solution actually works pretty well without loosing too much quality going from 2K+ down to 100px. Just adding `...WithOptions()` did the trick. – denikov Aug 10 '14 at 16:06
  • 2
    I find it interesting that after trying many complex solutions the 5 liner method was the one that works the best and has the best quality. – Eric Alford Jan 19 '15 at 06:03
0

Following the solution from ageektrapped, for PNG's transparent images, you should set the second parameter to NO/false for

UIGraphicsBeginImageContextWithOptions(..., NO, ...); 

will solve the black/white background issue

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Kohls
  • 820
  • 7
  • 19