How to ReSize Image with Good Quality in iPhone

2020-07-03 04:21发布

问题:

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;

}

回答1:

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;

}


回答2:

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