CCGraphics.m 18 KB

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