How to create CGImageRef from NSData string data (NOT UIImage)

☆樱花仙子☆ 提交于 2019-12-01 08:11:40

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

  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.

  2. 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);
    

    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).

  3. 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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!