如何在iOS中将字节数组转换为图像 [英] how to convert byte array to image in ios
问题描述
今天我的任务是将字节数组转换为图像
today my task is convert byte array to image
首先,我尝试将图像转换为字节数组:-
First I try to convert image to byte array :-
要将图像转换为字节数组,首先要做的是将特定的图像[UIImage
]转换为NSData
.然后,将NSData
转换为字节数组.在这里,我将给出示例代码,只需通过...
For converting Image to Byte array first we have to do is to convert that particular image [UIImage
] to NSData
.Then we will convert that NSData
to Byte array. Here I will give the sample code, just go through...
//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
i am try like this Convert byte to 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;
我有输出将图像转换为字节数组,但我想将字节数组转换为图像 所以请帮我谢谢.
I got output convert image to byte array but i want convert byte array to image so please help me thanks in advanced.
推荐答案
首先,您需要将字节转换为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];
这篇关于如何在iOS中将字节数组转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!