iOS图片更改尺寸并转Base64

2019-07-05  本文已影响0人  你的小福蝶

按照规定的图片尺寸,将图片转Base64上传。
目前问题:base64还原后尺寸并不准,不过不会出现失真问题。

调用

[self cerPhotoCompressToBase64StrByImage:image Size:CGSizeMake(330, 450) length:50000];

实现

-(NSString *)cerPhotoCompressToBase64StrByImage:(UIImage *)resultImage Size:(CGSize)size length:(NSUInteger)maxLength{
    
    //固定尺寸 - 尺寸压缩或放大
    CGSize newSize = CGSizeMake(size.width, resultImage.size.width*1.0*size.height/size.width);
    UIGraphicsBeginImageContext(newSize);
    
    [resultImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //满质量
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(self, compression);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
    
    //长度对比
    if (encodedImageStr.length<=maxLength) {
        return encodedImageStr;
    }
    
    //质量压缩
    while (encodedImageStr.length > maxLength && compression > 0) {
        compression -= 0.02;
        data = UIImageJPEGRepresentation(self, compression);
        encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
    }
    return encodedImageStr;
}
上一篇下一篇

猜你喜欢

热点阅读