美文网首页
iOS图片更改尺寸并转Base64

iOS图片更改尺寸并转Base64

作者: 你的小福蝶 | 来源:发表于2019-07-05 16:56 被阅读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;
}

相关文章

网友评论

      本文标题:iOS图片更改尺寸并转Base64

      本文链接:https://www.haomeiwen.com/subject/xzbehctx.html