获取 UIImage 的像素信息总是件麻烦事。让我们来解决这个问题吧!
使用 pod SYImageColorTools/GPUImage
,您可以选择从 GPUImageFramebuffer
对象的数据中获取相同的操作方法。
这是一个非常简洁的类,用于访问图像的像素。它的唯一目标是保持图像数据在内存中,这样如果需要获取多个像素,您就可以减少缓冲区分配的开销。
@interface SYImageColorGetter : NSObject
- (instancetype)initWithImage:(UIImage *)image;
- (UIColor *)getColorAtPoint:(CGPoint)point;
- (CGFloat)getRedAtPoint:(CGPoint)point;
- (CGFloat)getGreenAtPoint:(CGPoint)point;
- (CGFloat)getBlueAtPoint:(CGPoint)point;
- (CGFloat)getAlphaAtPoint:(CGPoint)point;
@end
允许从缓冲区获取像素值,该缓冲区由 OpenGL 纹理(例如,当使用 GPUImage 时)或 UIImage
创建。
它定义了多种类型
SYPixel
:包含 r,g,b 和 a 数据的结构体,表示一个像素SYImageInfo
:包含缓冲区所需信息以理解它的结构体,由 SYImageGetPixelValue
和 SYImageDetermineEdgeInsetsToTrimTransparentPixels
使用下面是头文件
typedef struct {
CGFloat r;
CGFloat g;
CGFloat b;
CGFloat a;
} SYPixel;
typedef struct {
NSUInteger width;
NSUInteger height;
NSUInteger bytesPerRow;
BOOL alphaOnly;
BOOL alphaFirst;
BOOL alphaPremultiplied;
BOOL bigEndian;
} SYImageInfo;
// Create a basic SYImageInfo struct for a GPUImage based buffer
SYImageInfo SYImageInfoCreateForOpenGLTexture(NSUInteger w, NSUInteger h);
// Get pixel value in a given buffer, understandable with the SYImageInfo parameter
SYPixel SYImageGetPixelValue(const uint8_t *data, SYImageInfo info, NSUInteger x, NSUInteger y, BOOL onlyAlpha);
// Returns the number of lines and columns to remove from the image on each side to remove all completely transparent lines
UIEdgeInsets SYImageDetermineEdgeInsetsToTrimTransparentPixels(const uint8_t *data, SYImageInfo imageInfo, CGFloat maxAlpha);
一个用于从一个 SYPixel
结构体创建 UIColor
的简单分类
@interface UIColor (SYImageColorTools)
+ (UIColor *)colorWithSYPixel:(SYPixel)pixel;
@end
为 SYImageColorTools
功能提供了高级方法的分类
@interface UIImage (SYImageColorTools)
- (SYImageInfo)imageInfo;
- (UIColor *)colorAtPoint:(CGPoint)pixelPoint;
- (UIImage *)imageByTrimmingTransparentPixels;
@end
对 GPUImage
的扩展,允许使用 SYImageColorTools
,让您可以从滤镜的 OpenGL 缓冲区中读取数据。
通过获取缓冲区和适当的图像信息,帮助使用 SYImageColorTools
与 GPUImageFramebuffer
。
typedef void(^SYImageBytesBlock)(GLubyte *bytes, SYImageInfo info);
@interface GPUImageFramebuffer (SYImageColorTools)
- (void)getBytes:(SYImageBytesBlock)block;
@end
这是一种 GPUImage
滤镜,每次机会计算裁剪区域,并允许您访问这些值。计算是在 CPU 上完成的,因为我不知道如何在 GPU 上进行裁剪。实际上并不执行裁剪,您需要使用 lastComputedCropRegion
属性来自行裁剪。抱歉 ¯`(ツ)¯
@interface SYGPUImageFilterWhiteSpaceTrimmer : GPUImageFilter
@property (nonatomic, assign) CGFloat maxAlpha;
@property (nonatomic, assign) CGRect lastComputedCropRegion;
@property (nonatomic, assign) CGRect lastComputedCropRegionNormalized;
@property (nonatomic, assign) BOOL cropRegionDefined;
@end