NSData转Byte数组分段上传

UIImage *image = [UIImage imageNamed:@"123"];
    NSData *data = UIImagePNGRepresentation(image);
    // 每次读取1024的长度
    NSInteger readLength = 1024;
    NSInteger count = data.length / readLength;
    
    NSMutableData *mutData = [NSMutableData data];
    char bytes[data.length];
    for (int i = 0; i < count; i++) {
        [data getBytes:bytes range:NSMakeRange(i * readLength, readLength)];
        NSData *newData = [NSData dataWithBytes:bytes length:readLength];
        [mutData appendData:newData];
    }
    // 最后剩余的部分
    NSInteger res = data.length % readLength;
    if (res > 0) {
        [data getBytes:bytes range:NSMakeRange(data.length - res, res)];
        NSData *newData = [NSData dataWithBytes:bytes length:res];
        [mutData appendData:newData];
    }
  
  NSLog(@"resulteData:%ld", mutData.length);



==================swift版本=======================

if let image = UIImage(named: "123"), let data = image.pngData(), data.count > 0 {

            let nsdata = data as NSData

            var bytes = [UInt8](repeating: 0, count: nsdata.count)

            nsdata.getBytes(&bytes, length: nsdata.count)

            

            let readLength = 1024

            

            let mutData = NSMutableData()

            let count = bytes.count / readLength

            for i in 0..<count {

                let start = i * readLength

                let values = bytes[start..<(start + readLength)]

                let value = NSData(bytes: Array(values), length: values.count)

                mutData.append(value as Data)

            }

            

            let reset = bytes.count % (readLength)

            if reset > 0 {

                let start = bytes.count - reset

                let values = bytes[start..<bytes.count]

                let value = NSData(bytes: Array(values), length: values.count)

                mutData.append(value as Data)

            }

            print("mutData.count:\(mutData.count)")

        }

 
 

 

posted on 2022-07-23 11:54  大圣ios博客  阅读(486)  评论(0编辑  收藏  举报