CCGraphics.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. //
  2. // CCGraphics.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/02/16.
  6. // Copyright (c) 2016 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCGraphics.h"
  24. #import "CCUtility.h"
  25. #import "NSString+TruncateToWidth.h"
  26. #import "NCBridgeSwift.h"
  27. @implementation CCGraphics
  28. + (UIImage *)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time
  29. {
  30. AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
  31. NSParameterAssert(asset);
  32. AVAssetImageGenerator *assetIG =
  33. [[AVAssetImageGenerator alloc] initWithAsset:asset];
  34. assetIG.appliesPreferredTrackTransform = YES;
  35. assetIG.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
  36. CGImageRef thumbnailImageRef = NULL;
  37. CFTimeInterval thumbnailImageTime = time;
  38. NSError *igError = nil;
  39. thumbnailImageRef =
  40. [assetIG copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&igError];
  41. if (!thumbnailImageRef) NSLog(@"[LOG] thumbnailImageGenerationError %@", igError );
  42. UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
  43. return thumbnailImage;
  44. }
  45. // mix two image
  46. + (UIImage *)overlayImage:(UIImage *)backgroundImage watermarkImage:(UIImage *)watermarkImage where:(NSString *)where
  47. {
  48. UIGraphicsBeginImageContext(backgroundImage.size);
  49. [backgroundImage drawInRect:CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height)];
  50. if ([where isEqualToString:@"right"]) [watermarkImage drawInRect:CGRectMake(backgroundImage.size.width - watermarkImage.size.width, backgroundImage.size.height - watermarkImage.size.height, watermarkImage.size.width, watermarkImage.size.height)];
  51. if ([where isEqualToString:@"left"]) [watermarkImage drawInRect:CGRectMake(0, backgroundImage.size.height - watermarkImage.size.height, backgroundImage.size.width - watermarkImage.size.width, backgroundImage.size.height - watermarkImage.size.height)];
  52. UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
  53. UIGraphicsEndImageContext();
  54. return result;
  55. }
  56. + (UIImage *)generateImageFromVideo:(NSString *)videoPath
  57. {
  58. NSURL *url = [NSURL fileURLWithPath:videoPath];
  59. NSError *error = NULL;
  60. AVURLAsset* asset = [AVURLAsset URLAssetWithURL:url options:nil];
  61. AVAssetImageGenerator* imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
  62. imageGenerator.appliesPreferredTrackTransform = YES;
  63. // CMTime time = CMTimeMake(1, 65);
  64. CGImageRef cgImage = [imageGenerator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:nil error:&error];
  65. if(error) return nil;
  66. UIImage* image = [UIImage imageWithCGImage:cgImage];
  67. CGImageRelease(cgImage);
  68. return image;
  69. }
  70. + (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)targetSize isAspectRation:(BOOL)aspect
  71. {
  72. CGFloat originRatio = image.size.width / image.size.height;
  73. CGFloat newRatio = targetSize.width / targetSize.height;
  74. CGSize sz;
  75. CGFloat scale = 1.0;
  76. if (!aspect) {
  77. sz = targetSize;
  78. }else {
  79. if (originRatio < newRatio) {
  80. sz.height = targetSize.height;
  81. sz.width = targetSize.height * originRatio;
  82. }else {
  83. sz.width = targetSize.width;
  84. sz.height = targetSize.width / originRatio;
  85. }
  86. }
  87. sz.width /= scale;
  88. sz.height /= scale;
  89. UIGraphicsBeginImageContextWithOptions(sz, NO, UIScreen.mainScreen.scale);
  90. [image drawInRect:CGRectMake(0, 0, sz.width, sz.height)];
  91. UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  92. UIGraphicsEndImageContext();
  93. return newImage;
  94. }
  95. + (UIImage *)createNewImageFrom:(NSString *)fileName ocId:(NSString *)ocId filterGrayScale:(BOOL)filterGrayScale typeFile:(NSString *)typeFile writeImage:(BOOL)writeImage
  96. {
  97. UIImage *originalImage;
  98. UIImage *scaleImage;
  99. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName];
  100. if (![CCUtility fileProviderStorageExists:ocId fileNameView:fileName]) return nil;
  101. // only viedo / image
  102. if (![typeFile isEqualToString: k_metadataTypeFile_image] && ![typeFile isEqualToString: k_metadataTypeFile_video]) return nil;
  103. if ([typeFile isEqualToString: k_metadataTypeFile_image]) {
  104. originalImage = [UIImage imageWithContentsOfFile:fileNamePath];
  105. }
  106. if ([typeFile isEqualToString: k_metadataTypeFile_video]) {
  107. // create symbolik link for read video file in temp
  108. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:@"tempvideo.mp4"] error:nil];
  109. [[NSFileManager defaultManager] linkItemAtPath:fileNamePath toPath:[NSTemporaryDirectory() stringByAppendingString:@"tempvideo.mp4"] error:nil];
  110. originalImage = [self generateImageFromVideo:[NSTemporaryDirectory() stringByAppendingString:@"tempvideo.mp4"]];
  111. }
  112. scaleImage = [self scaleImage:originalImage toSize:CGSizeMake(k_sizePreview, k_sizePreview) isAspectRation:YES];
  113. scaleImage = [UIImage imageWithData:UIImageJPEGRepresentation(scaleImage, 0.5f)];
  114. // it is request write photo ?
  115. if (writeImage && scaleImage) {
  116. if (filterGrayScale) {
  117. // if it is preview for Upload then trasform it in gray scale
  118. scaleImage = [self grayscale:scaleImage];
  119. [UIImageJPEGRepresentation(scaleImage, 0.5) writeToFile:<#(nonnull NSString *)#> atomically:<#(BOOL)#>]
  120. [UIImagePNGRepresentation(scaleImage) writeToFile:[CCUtility getDirectoryProviderStorageIconOcId:ocId fileNameView:fileName] atomically: YES];
  121. } else {
  122. [UIImagePNGRepresentation(scaleImage) writeToFile:[CCUtility getDirectoryProviderStorageIconOcId:ocId fileNameView:fileName] atomically: YES];
  123. }
  124. }
  125. return scaleImage;
  126. }
  127. + (UIColor *)colorFromHexString:(NSString *)hexString
  128. {
  129. unsigned rgbValue = 0;
  130. NSScanner *scanner = [NSScanner scannerWithString:hexString];
  131. [scanner setScanLocation:1]; // bypass '#' character
  132. [scanner scanHexInt:&rgbValue];
  133. return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
  134. }
  135. + (UIImage *)changeThemingColorImage:(UIImage *)image multiplier:(NSInteger)multiplier color:(UIColor *)color
  136. {
  137. CGRect rect = CGRectMake(0, 0, image.size.width*multiplier / (2 / UIScreen.mainScreen.scale), image.size.height*multiplier / (2 / UIScreen.mainScreen.scale));
  138. UIGraphicsBeginImageContext(rect.size);
  139. CGContextRef context = UIGraphicsGetCurrentContext();
  140. CGContextClipToMask(context, rect, image.CGImage);
  141. CGContextSetFillColorWithColor(context, [color CGColor]);
  142. CGContextFillRect(context, rect);
  143. UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
  144. UIGraphicsEndImageContext();
  145. return [UIImage imageWithCGImage:img.CGImage scale:UIScreen.mainScreen.scale orientation: UIImageOrientationDownMirrored];
  146. }
  147. + (UIImage *)changeThemingColorImage:(UIImage *)image width:(CGFloat)width height:(CGFloat)height color:(UIColor *)color
  148. {
  149. CGRect rect = CGRectMake(0, 0, width / (2 / UIScreen.mainScreen.scale), height / (2 / UIScreen.mainScreen.scale));
  150. UIGraphicsBeginImageContext(rect.size);
  151. CGContextRef context = UIGraphicsGetCurrentContext();
  152. CGContextClipToMask(context, rect, image.CGImage);
  153. if (color)
  154. CGContextSetFillColorWithColor(context, [color CGColor]);
  155. CGContextFillRect(context, rect);
  156. UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
  157. UIGraphicsEndImageContext();
  158. return [UIImage imageWithCGImage:img.CGImage scale:UIScreen.mainScreen.scale orientation: UIImageOrientationDownMirrored];
  159. }
  160. + (UIImage*)drawText:(NSString*)text inImage:(UIImage*)image colorText:(UIColor *)colorText sizeOfFont:(CGFloat)sizeOfFont
  161. {
  162. NSDictionary* attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:sizeOfFont], NSForegroundColorAttributeName:colorText};
  163. NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:text attributes:attributes];
  164. int x = image.size.width/2 - attributedString.size.width/2;
  165. int y = image.size.height/2 - attributedString.size.height/2;
  166. UIGraphicsBeginImageContext(image.size);
  167. [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
  168. CGRect rect = CGRectMake(x, y, image.size.width, image.size.height);
  169. [[UIColor whiteColor] set];
  170. [text drawInRect:CGRectIntegral(rect) withAttributes:attributes];
  171. UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  172. newImage = [UIImage imageWithCGImage:newImage.CGImage scale:2 orientation:UIImageOrientationUp];
  173. UIGraphicsEndImageContext();
  174. return newImage;
  175. }
  176. // ------------------------------------------------------------------------------------------------------
  177. // MARK: Blur Image
  178. // ------------------------------------------------------------------------------------------------------
  179. + (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur toSize:(CGSize)toSize
  180. {
  181. CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
  182. CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur" keysAndValues:kCIInputImageKey, inputImage, @"inputRadius", @(blur), nil];
  183. CIImage *outputImage = filter.outputImage;
  184. CIContext *context = [CIContext contextWithOptions:nil];
  185. CGImageRef outImage = [context createCGImage:outputImage fromRect:[outputImage extent]];
  186. UIImage *blurImage = [UIImage imageWithCGImage:outImage];
  187. return [CCGraphics scaleImage:blurImage toSize:toSize isAspectRation:YES];
  188. }
  189. // ------------------------------------------------------------------------------------------------------
  190. // MARK: Is Light Color
  191. // ------------------------------------------------------------------------------------------------------
  192. /*
  193. Color visibility can be determined according to the following algorithm:
  194. (This is a suggested algorithm that is still open to change.)
  195. Two colors provide good color visibility if the brightness difference and the color difference between the two colors are greater than a set range.
  196. Color brightness is determined by the following formula:
  197. ((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000
  198. Note: This algorithm is taken from a formula for converting RGB values to YIQ values. This brightness value gives a perceived brightness for a color.
  199. Color difference is determined by the following formula:
  200. (maximum (Red value 1, Red value 2) - minimum (Red value 1, Red value 2)) + (maximum (Green value 1, Green value 2) - minimum (Green value 1, Green value 2)) + (maximum (Blue value 1, Blue value 2) - minimum (Blue value 1, Blue value 2))
  201. */
  202. + (BOOL)isLight:(UIColor *)color
  203. {
  204. const CGFloat *componentColors = CGColorGetComponents(color.CGColor);
  205. CGFloat colorBrightness = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
  206. if (colorBrightness < 0.8) { // STD 0.5
  207. return false;
  208. } else {
  209. return true;
  210. }
  211. }
  212. + (UIImage *)grayscale:(UIImage *)sourceImage
  213. {
  214. /* const UInt8 luminance = (red * 0.2126) + (green * 0.7152) + (blue * 0.0722); // Good luminance value */
  215. /// Create a gray bitmap context
  216. const size_t width = (size_t)sourceImage.size.width;
  217. const size_t height = (size_t)sourceImage.size.height;
  218. const int kNyxNumberOfComponentsPerGreyPixel = 3;
  219. CGRect imageRect = CGRectMake(0, 0, sourceImage.size.width, sourceImage.size.height);
  220. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
  221. CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8/*Bits per component*/, width * kNyxNumberOfComponentsPerGreyPixel, colorSpace, kCGImageAlphaNone);
  222. CGColorSpaceRelease(colorSpace);
  223. if (!bmContext)
  224. return nil;
  225. /// Image quality
  226. CGContextSetShouldAntialias(bmContext, false);
  227. CGContextSetInterpolationQuality(bmContext, kCGInterpolationHigh);
  228. /// Draw the image in the bitmap context
  229. CGContextDrawImage(bmContext, imageRect, sourceImage.CGImage);
  230. /// Create an image object from the context
  231. CGImageRef grayscaledImageRef = CGBitmapContextCreateImage(bmContext);
  232. UIImage *grayscaled = [UIImage imageWithCGImage:grayscaledImageRef scale:sourceImage.scale orientation:sourceImage.imageOrientation];
  233. /// Cleanup
  234. CGImageRelease(grayscaledImageRef);
  235. CGContextRelease(bmContext);
  236. return grayscaled;
  237. }
  238. + (UIImage *)generateSinglePixelImageWithColor:(UIColor *)color
  239. {
  240. CGSize imageSize = CGSizeMake(1.0f, 1.0f);
  241. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0f);
  242. CGContextRef theContext = UIGraphicsGetCurrentContext();
  243. CGContextSetFillColorWithColor(theContext, color.CGColor);
  244. CGContextFillRect(theContext, CGRectMake(0.0f, 0.0f, imageSize.width, imageSize.height));
  245. CGImageRef theCGImage = CGBitmapContextCreateImage(theContext);
  246. UIImage *theImage;
  247. if ([[UIImage class] respondsToSelector:@selector(imageWithCGImage:scale:orientation:)]) {
  248. theImage = [UIImage imageWithCGImage:theCGImage scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
  249. } else {
  250. theImage = [UIImage imageWithCGImage:theCGImage];
  251. }
  252. CGImageRelease(theCGImage);
  253. return theImage;
  254. }
  255. + (void)addImageToTitle:(NSString *)title colorTitle:(UIColor *)colorTitle imageTitle:(UIImage *)imageTitle imageRight:(BOOL)imageRight navigationItem:(UINavigationItem *)navigationItem
  256. {
  257. UIView *navView = [UIView new];
  258. UILabel *label = [UILabel new];
  259. if (imageRight)
  260. title = [NSString stringWithFormat:@" %@", title];
  261. label.text = title;
  262. [label sizeToFit];
  263. label.center = navView.center;
  264. label.textColor = colorTitle;
  265. label.textAlignment = NSTextAlignmentCenter;
  266. CGFloat correct = 6;
  267. UIImageView *image = [UIImageView new];
  268. image.image = imageTitle;
  269. CGFloat imageAspect = image.image.size.width/image.image.size.height;
  270. if (imageRight) {
  271. image.frame = CGRectMake(label.intrinsicContentSize.width+label.frame.origin.x+correct, label.frame.origin.y+correct/2, label.frame.size.height*imageAspect-correct, label.frame.size.height-correct);
  272. } else {
  273. image.frame = CGRectMake(label.frame.origin.x-label.frame.size.height*imageAspect, label.frame.origin.y+correct/2, label.frame.size.height*imageAspect-correct, label.frame.size.height-correct);
  274. }
  275. image.contentMode = UIViewContentModeScaleAspectFit;
  276. [navView addSubview:label];
  277. [navView addSubview:image];
  278. navigationItem.titleView = navView;
  279. [navView sizeToFit];
  280. }
  281. + (void)settingThemingColor:(NSString *)themingColor themingColorElement:(NSString *)themingColorElement themingColorText:(NSString *)themingColorText
  282. {
  283. UIColor *newColor, *newColorElement, *newColorText;
  284. // COLOR
  285. if (themingColor.length == 7) {
  286. newColor = [CCGraphics colorFromHexString:themingColor];
  287. } else {
  288. newColor = NCBrandColor.sharedInstance.customer;
  289. }
  290. // COLOR TEXT
  291. if (themingColorText.length == 7) {
  292. newColorText = [CCGraphics colorFromHexString:themingColorText];
  293. } else {
  294. newColorText = NCBrandColor.sharedInstance.customerText;
  295. }
  296. // COLOR ELEMENT
  297. if (themingColorElement.length == 7) {
  298. newColorElement = [CCGraphics colorFromHexString:themingColorElement];
  299. } else {
  300. if ([themingColorText isEqualToString:@"#000000"])
  301. newColorElement = [UIColor blackColor];
  302. else
  303. newColorElement = newColor;
  304. }
  305. NCBrandColor.sharedInstance.brand = newColor;
  306. NCBrandColor.sharedInstance.brandElement = newColorElement;
  307. NCBrandColor.sharedInstance.brandText = newColorText;
  308. }
  309. @end
  310. // ------------------------------------------------------------------------------------------------------
  311. // MARK: Avatar
  312. // ------------------------------------------------------------------------------------------------------
  313. @implementation CCAvatar
  314. - (id)initWithImage:(UIImage *)image borderColor:(UIColor*)borderColor borderWidth:(float)borderWidth
  315. {
  316. self = [super initWithImage:image];
  317. float cornerRadius = self.frame.size.height/2.0f;
  318. CALayer *layer = [self layer];
  319. [layer setMasksToBounds:YES];
  320. [layer setCornerRadius: cornerRadius];
  321. [layer setBorderWidth: borderWidth];
  322. [layer setBorderColor:[borderColor CGColor]];
  323. return self;
  324. }
  325. @end