开发者

Fasted way to detect and remove transparent space around NSImage

What is the fastest way to trim an image (NSImage or CGImageRef) so that all transparent areas around the image are removed?

I'd imagine I could look at each pixel starting from the top and determine its alpha value, but maybe there's another (faster) way.

Thanks, Mark.

PS: My usecase:

I'm using QLThumbnailImageCreate开发者_如何转开发 to generate thumbnails of files. The problem is that all images returned by that call are of equal width and height.

For example, if I create a thumbnail for a photo of the dimensions 300x500, the resulting preview would be of the same width and height with transparent areas added at the top and bottom to preserve the aspect ratio.


It's actually really fast to iterate over the pixels in an image if you just get a pointer to the raw pixel data. Even on iOS devices this is pretty quick.

Using a CGImageRef you'd get the pixel data like this:

CFDataRef imageData = CGDataProviderCopyData(CGImageGetDataProvider(anImage)); 
const UInt32 *pixels = (const UInt32*)CFDataGetBytePtr(imageData);

and you can just iterate through it:

for (int j = 0; j < (anImageHeight * anImageWidth); j++)
{
    if (pixels[j] & 0xff000000)
    {
    //this is not a transparent pixel
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜