来自字节数组的 CGImage [英] CGImage from byte array

查看:41
本文介绍了来自字节数组的 CGImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用标准图像格式(jpeg、gif、png 等)从文件加载 CGImage 或 NSImage 非常简单.

Loading a CGImage or NSImage from a file using a standard image format (jpeg, gif, png et.) is all very simple.

但是,我现在需要从使用 libfreetype 生成的内存中的字节数组创建一个 CGImage.从格式化字节数组创建 OpenGL 纹理真的很容易,我可以看到如何创建一个 CGBitmapContext 来写入.但我似乎找不到从原始像素数组创建 CGImage 的简单方法.

However, I now need to create a CGImage from an array in bytes in memory generated using libfreetype. Its really easy to create OpenGL textures from an array of formatted bytes, and I can see how to create a CGBitmapContext to write to. But I can't seem to find an easy way to create a CGImage from a raw pixel array.

推荐答案

您可以创建一个 CGDataProvider,让 CG 从您的提供者那里请求必要的数据,而不是写入图像缓冲区.

You can create a CGDataProvider, and let CG request the necessary data from your provider, instead of writing to an image buffer.

这是一个非常简单的例子,它生成一个大小为 64x64 的黑色 CGImage.

Here's a very simple example that generates a black CGImage of size 64x64.

CGDataProviderSequentialCallbacks callbacks;
callbacks.getBytes = getBytes;

CGDataProviderRef provider = CGDataProviderCreateSequential(NULL, &callbacks);
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGImageRef img = CGImageCreate(64,                         // width
                               64,                         // height
                               8,                          // bitsPerComponent
                               24,                         // bitsPerPixel
                               64*3,                       // bytesPerRow
                               space,                      // colorspace
                               kCGBitmapByteOrderDefault,  // bitmapInfo
                               provider,                   // CGDataProvider
                               NULL,                       // decode array
                               NO,                         // shouldInterpolate
                               kCGRenderingIntentDefault); // intent

CGColorSpaceRelease(space);
CGDataProviderRelease(provider);

// use the created CGImage

CGImageRelease(img);

和 getBytes 定义如下:

and getBytes is defined like this:

size_t getBytes(void *info, void *buffer, size_t count) {
    memset(buffer, 0x00, count);
    return count;
}

当然,您需要实现其他回调(skipForwardrewindreleaseInfo),并使用适当的结构或对象信息.

of course, you will want to implement the other callbacks (skipForward, rewind, releaseInfo), and use a proper structure or object for info.

有关更多信息,请查看 CGImageCGDataProvider 引用.

For more information, check out the CGImage and CGDataProvider references.

这篇关于来自字节数组的 CGImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆