且构网

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

如何从NSData字符串数据创建CGImageRef(不是UIImage)

更新时间:2022-05-19 04:35:58

简短的答案,因为这主要是针对我在NSChat中提到的内容:

Short-ish answer, since this is mostly just going over what I mentioned in NSChat:

  1. 弄清楚所接收图像的格式以及其大小(宽度和高度,以像素为单位).您在聊天中提到这只是ARGB8的直接数据,因此请记住这一点.我不确定您如何收到其他信息.

  1. Figure out what the format of the image you're receiving is as well as its size (width and height, in pixels). You mentioned in chat that it's just straight ARGB8 data, so keep that in mind. I'm not sure how you're receiving the other info, if at all.

使用CGImageCreate,使用已经知道的图像来创建新图像(即,大概知道其宽度,高度等等,如果不知道,则应将其与您要发送的图片).例如,没人喜欢写的这个样板包:

Using CGImageCreate, create a new image using what you know about the image already (i.e., presumably you know its width, height, and so on — if you don't, you should be packing this in with the image you're sending). E.g., this bundle of boilerplate that nobody likes to write:

// NOTE: have not tested if this even compiles -- consider it pseudocode.

CGImageRef image;
CFDataRef bridgedData;
CGDataProviderRef dataProvider;
CGColorSpaceRef colorSpace;
CGBitmapInfo infoFlags = kCGImageAlphaFirst; // ARGB

// Get a color space
colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
// Assuming the decoded data is only pixel data
bridgedData  = (__bridge CFDataRef)decodedData;
dataProvider = CGDataProviderCreateWithCFData(bridgedData);

// Given size_t width, height which you should already have somehow
image = CGImageCreate(
    width, height, /* bpc */ 8, /* bpp */ 32, /* pitch */ width * 4,
    colorSpace, infoFlags,
    dataProvider, /* decode array */ NULL, /* interpolate? */ TRUE,
    kCGRenderingIntentDefault /* adjust intent according to use */
  );

// Release things the image took ownership of.
CGDataProviderRelease(dataProvider);
CGColorSpaceRelease(colorSpace);

编写该代码时应保证它是ARGB_8888,数据是正确的,没有任何东西可能返回NULL,等等.复制/粘贴上面的代码可能会导致半径3英里范围内的所有内容爆炸.错误处理取决于您自己(例如CGColorSpaceCreateWithName可能返回null).

That code's written with the idea that it's guaranteed to be ARGB_8888, the data is correct, nothing could possibly return NULL, etc. Copy/pasting the above code could potentially cause everything in a three mile radius to explode. Error handling's up to you (e.g., CGColorSpaceCreateWithName can potentially return null).

使用CGImage分配UIImage.由于UIImage将拥有CGImage的所有权/复制该CGImage,因此释放您的CGImageRef(实际上,文档对 UIImage对CGImage所做的事情一无所知,但是您将不再使用它,因此您必须释放您的).

Allocate a UIImage using the CGImage. Since the UIImage will take ownership of/copy the CGImage, release your CGImageRef (actually, the docs say nothing about what UIImage does with the CGImage, but you're not going to use it anymore, so you must release yours).