IOS图片转成字符串和字符串转回图片

IOS图片转base64字符串和字符串转回图片
最近在使用扫描二维码存储的时候遇到了如下问题:我需要将扫描到的图片和照片保存下来,我想到了用轻量级的数组存储NSUserDefaults。但是遇到一个问题就是,NSUserDefaults支持的数据格式有:NSNumber(Integer、Float、Double),NSString,NSDate,NSArray,NSDictionary,BOOL类型。其他类型不支持,而且即便是存到数组字典或者Data中也不行。
后来就将图片转换成了字符串然后存model中,再把model存到数组中,数组存到NSUserDefaults中,在记录界面读取。

转换成字符串

UIImage *_originImage = [UIImage imageNamed:@"full_playlist_hl.png"];

NSData *_data = UIImageJPEGRepresentation(_originImage, 1.0f);

NSString *_encodedImageStr = [_data base64Encoding];

NSLog(@"===Encoded image:\n%@", _encodedImageStr);

字符串转换成image

NSData *_decodedImageData   = [[NSData alloc] initWithBase64Encoding:_encodedImageStr];

//上边的方法7.0之后弃用了,可以使用下边这个方法
//NSData * a = [[NSData alloc] initWithBase64EncodedString:newDic[@"image"] options:(NSDataBase64DecodingIgnoreUnknownCharacters)];

UIImage *_decodedImage      = [UIImage imageWithData:_decodedImageData];

NSLog(@"===Decoded image size: %@", NSStringFromCGSize(_decodedImage.size));

如果没有base64Encoding,可以手动添加

- (NSString *) base64Encoding {
    return [self base64EncodingWithLineLength:0];
}

- (NSString *) base64EncodingWithLineLength:(unsigned int) lineLength {
    const unsigned char    *bytes = [self bytes];
    NSMutableString *result = [NSMutableString stringWithCapacity:[self length]];
    unsigned long ixtext = 0;
    unsigned long lentext = [self length];
    long ctremaining = 0;
    unsigned char inbuf[3], outbuf[4];
    short i = 0;
    short charsonline = 0, ctcopy = 0;
    unsigned long ix = 0;

    while( YES ) {
        ctremaining = lentext - ixtext;
        if( ctremaining <= 0 ) break;

        for( i = 0; i < 3; i++ ) {
            ix = ixtext + i;
            if( ix < lentext ) inbuf[i] = bytes[ix];
            else inbuf [i] = 0;
        }

        outbuf [0] = (inbuf [0] & 0xFC) >> 2;
        outbuf [1] = ((inbuf [0] & 0x03) << 4) | ((inbuf [1] & 0xF0) >> 4);
        outbuf [2] = ((inbuf [1] & 0x0F) << 2) | ((inbuf [2] & 0xC0) >> 6);
        outbuf [3] = inbuf [2] & 0x3F;
        ctcopy = 4;

        switch( ctremaining ) {
            case 1: 
                ctcopy = 2; 
                break;
            case 2: 
                ctcopy = 3; 
                break;
        }

        for( i = 0; i < ctcopy; i++ )
            [result appendFormat:@"%c", encodingTable[outbuf[i]]];

        for( i = ctcopy; i < 4; i++ )
            [result appendFormat:@"%c",'='];

        ixtext += 3;
        charsonline += 4;

        if( lineLength > 0 ) {
            if (charsonline >= lineLength) {
                charsonline = 0;
                [result appendString:@"\n"];
            }
        }
    }

    return result;
}

你可能感兴趣的:(ImageView)