图片像素操作

将白底图片转化为透明底图片

#define Mask8(x) ( (x) & 0xFF)
#define R(x) ( Mask8(x) )
#define G(x) ( Mask8(x >> 8 ) )
#define B(x) ( Mask8(x >> 16) )
#define A(x) ( Mask8(x >> 24) )
#define RGBAMake(r, g, b, a) ( Mask8(r) | Mask8(g) << 8 | Mask8(b) << 16 | Mask8(a) << 24 )
// 白底转为透明底
+ (UIImage *)writeToAlphaByImage:(UIImage *)image{
    //1.获得图片的像素 以及上下文
    UInt32 *inputPixels;
    CGImageRef inputCGImage = [image CGImage];
    size_t w = CGImageGetWidth(inputCGImage);
    size_t h = CGImageGetHeight(inputCGImage);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    NSInteger bytesPerPixel = 4;//每个像素的字节数
    NSInteger bitsPerComponent = 8;//每个组成像素的 位深
    NSInteger bitmapBytesPerRow = w * bytesPerPixel;//每行字节数
    inputPixels = (UInt32 *)calloc(w * h , sizeof(UInt32));//通过calloc开辟一段连续的内存空间
    CGContextRef context = CGBitmapContextCreate(inputPixels, w, h, bitsPerComponent, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), inputCGImage);
    //2操作像素
    for (NSInteger j = 0; j < h; j ++) {
        for (NSInteger i = 0 ; i < w; i ++) {
            UInt32 *currentPixel = inputPixels + (w * j) + i;
            UInt32 color = *currentPixel;
            // 如果是白色就转化为透明
            //灰度图(举例)
            UInt32 r = R(color);
            UInt32 g = G(color);
            UInt32 b = B(color);
            if (!(r==255&&g==255&&b==255)) continue;
            *currentPixel = RGBAMake(0, 0, 0, 1);
        }
    }
    //3从上下文中取出
    CGImageRef newImageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    
    //4释放
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    free(inputPixels);
    return newImage;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,831评论 25 709
  • 7.1 压缩图片 一、基础知识 1、图片的格式 jpg:最常见的图片格式。色彩还原度比较好,可以支持适当压缩后保持...
    AndroidMaster阅读 7,334评论 0 13
  • 在万达,和妹妹们吃饱撑着没事,看到有VR(Virtual Reality)虚拟现实游戏,于是交了30元,体验15分...
    净彻阅读 5,998评论 13 38
  • 感赏女儿今天在我的劝阻之下,最终没把手机带到学校去 。感赏自己能够在关键时候做到温柔地坚持。 感赏...
    静等花开之心路阅读 1,410评论 1 3
  • 伟大的人不是生下来就伟大,而是在成长的过程中显示其伟大 富人的思维其实是从穷到富的奋斗过程,磨练出来的一些品格和思...
    驰骋峰财阅读 3,184评论 0 0