//
//  UIImage+Extension.m
//  SmartLightForBigFish
//
//  Created by coderYK on 2017/8/7.
//  Copyright © 2017年 RD-iOS. All rights reserved.
//

#import "UIImage+Extension.h"
#import "RDSRgbColor.h"

@implementation UIImage (Extension)

+ (UIImage *)rds_imageWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+ (UIImage *)rds_imageWithColor:(UIColor *)startColor toColor:(UIColor *)toColor imgSize:(CGSize)imgSize{
    
    NSMutableArray *ar = [NSMutableArray array];
    
    [ar addObject:(id)startColor.CGColor];
    [ar addObject:(id)toColor.CGColor];
    
    
    UIGraphicsBeginImageContextWithOptions(imgSize, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([toColor CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    
    CGPoint start;
    CGPoint end;
    //TopToBottom
    //start = CGPointMake(0.0, 0.0);
    //end = CGPointMake(0.0, imgSize.height);
    
    //LeftToRight
    start = CGPointMake(0.0, 0.0);
    end = CGPointMake(imgSize.width, 0.0);
    
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)rds_imageWithName:(NSString *)imageName andBackgroundColor:(UIColor *)backgroundColor {
    
    UIImage *image = [UIImage imageNamed:imageName];
    CGFloat imageWH = image.size.width*1.5;
    CGRect frame = CGRectMake(0, 0, imageWH, imageWH);
    
    UIGraphicsBeginImageContext(frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    [[UIColor clearColor] set];
    CGContextFillRect(context, frame);
    
    CGContextAddEllipseInRect(context, frame);
    [backgroundColor set];
    CGContextFillPath(context);
    
    
    [image drawInRect:CGRectMake((imageWH-image.size.width)*0.5, (imageWH-image.size.height)*0.5, image.size.width, image.size.height)];
    
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+ (UIImage *)rds_creatQRCodeWithData:(NSData *)data withSize:(CGFloat)size {
    
    // 1.实例化一个滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.恢复滤镜的默认属性
    [filter setDefaults];
    
    // 4.通过 KVO 设置滤镜的 inputMessage 数据
    [filter setValue:data forKey:@"inputMessage"];
    
    // 5.获得滤镜输出的图像
    CIImage *outImage = [filter outputImage];
    
    // 6.将 CIImage 转为 UIImage
    return [self createNonInterpolatedUIImageFormCIImage:outImage withSize:size];
}

+ (UIImage *)rds_creatQRCodeWithString:(NSString *)string withSize:(CGFloat)size {
    
    // 1.实例化一个滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.恢复滤镜的默认属性
    [filter setDefaults];
    
    // 3.输入的字符串转换为二进制数据
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    // 4.通过 KVO 设置滤镜的 inputMessage 数据
    [filter setValue:data forKey:@"inputMessage"];
    
    // 5.获得滤镜输出的图像
    CIImage *outImage = [filter outputImage];
    
    // 6.将 CIImage 转为 UIImage
    return [self createNonInterpolatedUIImageFormCIImage:outImage withSize:size];
}

/**
 *  传入CIImage,并指定对应的缩放比例
 *
 *  @param image CIImage 对象
 *  @param size  缩放系数
 *
 *  @return 返回经过缩放处理的 UIImage 对象
 */
+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 创建bitmap;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 保存bitmap到图片

    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    CGColorSpaceRelease(cs);
    
    CGImageRelease(bitmapImage);
    
    UIImage *outputImage = [UIImage imageWithCGImage:scaledImage];
    CGImageRelease(scaledImage);
    
    return outputImage;
}


+ (UIImage *)rds_renderingOriginalimageWithName:(NSString *)imageName {
    
    UIImage *image = [UIImage imageNamed:imageName];
    return [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

- (RDSRgbColor *)rds_colorAtPixel:(CGPoint)point {
    
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point)) { return nil; }
    
    NSInteger pointX = trunc(point.x);
    NSInteger pointY = trunc(point.y);
    CGImageRef cgImage = self.CGImage;
    NSUInteger width = self.size.width;
    NSUInteger height = self.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * 1;
    NSUInteger bitsPerComponent = 8;
    unsigned char pixelData[4] = { 0, 0, 0, 0 };
    CGContextRef context = CGBitmapContextCreate(pixelData, 1, 1, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy);
    CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
    CGContextRelease(context);
    CGFloat red = (int)pixelData[0];
    if (red < 5) {
        red = 5;
    }
    CGFloat green = (int)pixelData[1];
    if (green < 5) {
        green = 5;
    }
    CGFloat blue = (int)pixelData[2];
    if (blue < 5) {
        blue = 5;
    }
    CGFloat alpha = (int)pixelData[3];
    
    //    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    return [RDSRgbColor rds_rgbColorWithRgbArr:@[@(red), @(green), @(blue), @(alpha)]];
}


- (UIImage *)rds_imageScaleToSize:(CGSize)size{
    
    UIImage *image = self;
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0,0, size.width, size.height)];
    UIImage *scaleImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaleImage;
}

- (UIImage *)rds_changeColorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue{
    
    UIImage *image = self;
    const int imageWidth = image.size.width;
        const int imageHeight = image.size.height;
        size_t      bytesPerRow = imageWidth * 4;
        uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                                     kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
        CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
        // 遍历像素
        int pixelNum = imageWidth * imageHeight;
        uint32_t* pCurPtr = rgbImageBuf;
        for (int i = 0; i  < pixelNum; i++, pCurPtr++){
            if ((*pCurPtr & 0xFFFFFF00) <  0x99999900)    // 将白色变成透明
            {
                // 改成下面的代码，会将图片转成想要的颜色
                uint8_t* ptr = (uint8_t*)pCurPtr;
                ptr[3] = red; //0~255
                ptr[2] = green;
                ptr[1] = blue;
            }
            else
            {
                uint8_t* ptr = (uint8_t*)pCurPtr;
                ptr[0] = 0;
            }
        }
        // 输出图片
        CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
        CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,
                                            kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,
                                            NULL, true, kCGRenderingIntentDefault);
        CGDataProviderRelease(dataProvider);
        UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
        // 清理空间
        CGImageRelease(imageRef);
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);
        return resultUIImage;

}

void ProviderReleaseData (void *info, const void *data, size_t size){
    free((void*)data);
}

@end
