且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式调整图像像素大小

更新时间:2022-12-30 21:35:04

我使用像下面这样的功能来获取任何大小的图像。
原始图像应该比你想要的要大(ps:你可以尝试一个图像)

  +(UIImage * )thumbnailWithImageWithoutScale:(UIImage *)图像大小:(CGSize)wantSize 
{
UIImage * targetImage;
if(nil == image){
targetImage = nil;
} else {
CGSize size = image.size;
CGRect rect;
if(wantSize.width / wantSize.height> size.width / size.height){
rect.size.width = wantSize.height * size.width / size.height;
rect.size.height = wantSize.height;
rect.origin.x =(wantSize.width - rect.size.width)/ 2;
rect.origin.y = 0;
} else {
rect.size.width = wantSize.width;
rect.size.height = wantSize.width * size.height / size.width;
rect.origin.x = 0;
rect.origin.y =(wantSize.height - rect.size.height)/ 2;
}
UIGraphicsBeginImageContext(wantSize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context,[[UIColor clearColor] CGColor]);
UIRectFill(CGRectMake(0,0,wantSize.width,wantSize.height)); //清除背景
[image drawInRect:rect];
targetImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return targetImage;
}


i am creating app using facebook. if i am trying to upload photo to facebook means i got following message any give idea for solve that

"The provided user_generated photo for an OG action must be at least 480px in both dimensions"

I use a function like follow to get an image with any size. Original image should big than you wanted.(ps:You can try an image little)

+ (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)wantSize
{
    UIImage * targetImage;
    if (nil == image) {
        targetImage = nil;
    }else{
        CGSize size = image.size;
        CGRect rect;
        if (wantSize.width/wantSize.height > size.width/size.height) {
            rect.size.width = wantSize.height*size.width/size.height;
            rect.size.height = wantSize.height;
            rect.origin.x = (wantSize.width - rect.size.width)/2;
            rect.origin.y = 0;
        } else{
            rect.size.width = wantSize.width;
            rect.size.height = wantSize.width*size.height/size.width;
            rect.origin.x = 0;
            rect.origin.y = (wantSize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(wantSize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, wantSize.width, wantSize.height));//clear background
        [image drawInRect:rect];
        targetImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return targetImage;
}