uiimage 转换为像素数据 以及从像素数据生成为uiimage

生成RGBABitmapContext 
 CGContextRef CreateRGBABitmapContext (CGImageRef inImage){ 
CGContextRef context = NULL; CGColorSpaceRef colorSpace;
void *bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
size_t pixelsWide = CGImageGetWidth(inImage);
size_t pixelsHigh = CGImageGetHeight(inImage);
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();  if (colorSpace == NULL){
fprintf(stderr, "Error allocating color space");
return NULL;
}

// allocate the bitmap & create context
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL){
printf (stderr, "Memory not allocated!");
CGColorSpaceRelease( colorSpace );
return NULL;
}

context = CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
8,
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);

if (context == NULL){
    free (bitmapData);
    fprintf (stderr, "Context not created!");
 }

CGColorSpaceRelease( colorSpace );

 return context;
生成图片的像素数据
 // Return Image Pixel data as an RGBA bitmap
unsigned char *RequestImagePixelData(UIImage *inImage) {

CGImageRef img = [inImage CGImage];
CGSize size = [inImage size];
CGContextRef cgctx = CreateRGBABitmapContext(img); 
if (cgctx == NULL)
return NULL;

CGRect rect = {{0,0},{size.width, size.height}};
CGContextDrawImage(cgctx, rect, img);
unsigned char *data = CGBitmapContextGetData (cgctx);
CGContextRelease(cgctx);
return data;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
UIImage是iOS中的一个类,用于表示图像或照片。你可以使用UIImage来加载、显示和处理图像。下面是一些使用UIImage的常见操作: 1. 加载图像: 你可以使用UIImage(named:)方法从应用程序的资源中加载图像文件,例如: ``` let image = UIImage(named: "imageName") ``` 也可以使用UIImage(contentsOfFile:)方法从应用程序的沙盒中加载图像文件。 2. 显示图像: 你可以将UIImage对象分配给UIImageView的image属性,然后将UIImageView添加到视图层次结构中以显示图像,例如: ``` let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) imageView.image = image view.addSubview(imageView) ``` 3. 调整图像大小: 你可以使用UIImage的resizableImage(withCapInsets:resizingMode:)方法来调整图像的大小。这个方法会返回一个可调整大小的新图像,例如: ``` let resizedImage = image.resizableImage(withCapInsets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), resizingMode: .stretch) ``` 4. 图像处理: UIImage还提供了一些方法来进行图像处理,例如: - 使用UIImageJPEGRepresentation(_:compressionQuality:)方法将图像转换为JPEG格式的数据。 - 使用UIImagePNGRepresentation(_:)方法将图像转换为PNG格式的数据。 - 使用draw(in:)方法在指定的矩形中绘制图像。 以上是UIImage的一些常见用法,希望对你有帮助。如果你有具体的问题或需求,可以提供更多详细的信息,我会尽力帮助你。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值