如何将字节数组转换为ios中的图像
今天我的任务是将字节数组转换为图像
首先我尝试将图像转换为字节数组:
为了将Image转换为Byte数组,我们首先需要将特定的图像[ UIImage
]转换为NSData
。然后我们将该NSData
转换为Byte数组。 在这里,我将给出示例代码,只是通过…
//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];
而且我build议你在问题发生时应该首先查询文件。
这里是所有:
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];
您用错误的格式表示数据
您的图像格式为jpg
,您使用的是PNG
数据。
对于jpg
或jpeg
格式,您应该使用UIImageJPEGRepresentation
NSData * UIImageJPEGRepresentation ( UIImage *image, CGFloat compressionQuality );
所需的声明将是
NSData *imageData = UIImageJPEGRepresentation(image, 0.0f);// Set Compression quality to 0.0. You can change it.
对于png
格式,你应该使用UIImagePNGRepresentation
NSData * UIImagePNGRepresentation ( UIImage *image );
所需的声明将是
NSData *imageData = UIImagePNGRepresentation(image);
要将NSData
转换回UIImage
,请使用
UIImage *image = [UIImage imageWithData:imageData];
阅读苹果文档 。 看图像操作