且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-17 14:49:17

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

First, you need to convert bytes to NSData

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

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

Then, convert the data back to image.

UIImage *image = [UIImage imageWithData:imageData];

我建议您在出现问题时首先搜索文档.

And I suggest you should first searching about the documentations when problems occur.

仅此而已:

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];