我正在尝试获取图像中的突出颜色。最初,我试图获得this post中的颜色设置。但我的客户对它并不满意,因为它只返回平均颜色集,而不是确切的颜色。因此,现在我试图通过在this link.中找到的逻辑来获取主色集,但问题是代码是用jQuery和JavaScript编写的。它似乎很容易在web中实现,因为代码非常简单,如下所示
myImage = $('#myImage');
dominantColor = getDominantColor(myImage);
paletteArray = createPalette(myImage, 10); // 2nd argument sets # of colors in palette
我浏览了如何在iOS中执行JS,并参考了this link和this link,如下所示
[_webView loadHTMLString:@"<script src=\"color-thief.js\"></script>" baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];
NSString * imgName = [[NSBundle mainBundle] pathForResource:@"4" ofType:@"jpg"];
// UIImage * img = [UIImage imageNamed:imgName];
int colorCount = 9;
NSString *function1 =[[NSString alloc] initWithFormat: @"createPalette(%@, %d)", imgName, colorCount];
// NSString *function2 = [[NSString alloc] initWithFormat: @"getAverageRGB(%@)", imgName];
NSString *result = [_webView stringByEvaluatingJavaScriptFromString:function1];
NSLog(@"%@ result %@", result, [_webView stringByEvaluatingJavaScriptFromString:funcion1]);
但是我没有得到任何结果。它是空的。我遗漏了什么?有人能告诉我哪里出了问题吗?任何及时的帮助都是非常感谢的。提前谢谢。
发布于 2013-05-20 16:13:38
是否确定您的网页确实加载了jQuery库(从磁盘或联机)?
您可以使用safari调试webview,以检查当webview在模拟器中或在您的设备上打开时出现了什么问题。Here's a guide from apple帮助您入门。
发布于 2015-10-14 00:12:50
我也有同样的问题。您需要一些不同的函数来显式地在getPalette的末尾创建HTMLImageElement
和.toString()
。还有一些奇怪的Safari行为,它只在第二次拍摄时起作用:
let function = "var colorThief = new ColorThief(); var image = new Image(); image.src='\(imgName)'; colorThief.getPalette(image, 5).toString();"
let result1 = self.webView.stringByEvaluatingJavaScriptFromString(function)!
// for some reason result1 is always empty, but if we evaluate the same function second time after some time interval we will get the results.
sleep(1)
let result2 = self.webView.stringByEvaluatingJavaScriptFromString(function)!
// result2 is string of rgb components separated by commas
https://stackoverflow.com/questions/11739077
复制相似问题