ios - 如何在ios中将字节数组转换为图像

标签 ios uiimage arrays nsdata

今天我的任务是将字节数组转换为图像

首先我尝试将图像转换为字节数组:-

为了将图像转换为字节数组,我们首先要做的是将特定图像 [UIImage] 转换为 NSData。然后我们将转换那个 NSData 到字节数组。这里我给出示例代码,通过...

//Converting UIImage to NSData
    UIImage *image = [UIImage imageNamed: @"photo-04.jpg"];

    NSData *imageData = UIImagePNGRepresentation(image);

    //Converting NSData to Byte array
    NSUInteger len = [imageData length];
    NSLog(@"Byte Lendata1  %lu",(unsigned long)len);

    Byte *byteData = (Byte*)malloc(len);
    memcpy(byteData, [imageData bytes], len);

我正在尝试将字节转换为 imageView

 const unsigned char *bytes = [imageData bytes];

    NSUInteger length = [imageData length];

    NSMutableArray *byteArray = [NSMutableArray array];

    for (NSUInteger i = 0; i < length; i++) {
        [byteArray addObject:[NSNumber numberWithUnsignedChar:bytes[i]]];
    }
    NSDictionary *dictJson = [NSDictionary dictionaryWithObjectsAndKeys:
                              byteArray, @"photo",
                              nil];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictJson options:0 error:NULL];
    NSLog(@"");
    UIImage *image1 = [UIImage imageWithData:jsonData];

    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];


    imgView.image=image1;

我得到了将图像转换为字节数组的输出,但我想将字节数组转换为图像 所以请先帮助我谢谢。

最佳答案

首先,您需要将字节转换为NSData

NSData *imageData = [NSData dataWithBytes:bytesData length:length];

然后,将数据转换回图像。

UIImage *image = [UIImage imageWithData:imageData];

而且我建议大家在出现问题的时候先去查资料。

这里是全部:

UIImage *image = [UIImage imageNamed:@"RAC.png"];

NSData *imageData = UIImagePNGRepresentation(image);
// UIImageJPGRepresentation also work

NSInteger length = [imageData length];

Byte *byteData = (Byte*)malloc(length);
memcpy(byteData, [imageData bytes], length);

NSData *newData = [NSData dataWithBytes:byteData length:length];

UIImage *newImage = [UIImage imageWithData:newData];

UIImageView *imageView = [[UIImageView alloc] initWithImage:newImage];
imageView.frame = CGRectMake(50, 50, 100, 100);
[self.view addSubview:imageView];

关于ios - 如何在ios中将字节数组转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22316608/

相关文章:

ios - TableView编辑模式删除按钮重叠

ios - CloudKit "Couldn' t 仅在设备上获取签名证书

C++ 嵌入式系统摩尔斯电码

javascript - jQuery - split() 数组只有一个匹配 = 未定义

ios - Facebook Graph 请求无法在 iOS 9.2 中检索电子邮件 - xCode 7

ios - 以编程方式打开 iOS Touch ID 设置

ios - 如何检测 UIImage 的非透明部分何时与 UIImage 的另一个非透明部分接触

objective-c - 在 UITableView 中的 UIImageView 中从网络加载图像

ios - UIButton 图片饱和度变化

c++ - const 数组如何能够在每个元素中仅包含字符,而 char* 数组却能够在每个元素中指向字符串?