CCGraphics.m 16 KB

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