1

I am trying to get the prominent colors in an image. Initially I was trying to get the color set as in this post. But my client is not satisfied with it as it returns only the average color set and not the exact color. Hence now Im trying to get the dominant color set by the logic found in this link. But the problem is that the code is in jQuery and JavaScript. Seems its easy to implement in the web as the code is very simple as

myImage = $('#myImage');
dominantColor = getDominantColor(myImage);
paletteArray = createPalette(myImage, 10); // 2nd argument sets # of colors in palette

I surfed how to execute JS in iOS and did in reference to this link and this link and did as below

[_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]);

But I couldn't get any result. Its null. What am I missing? Can some one point me what went wrong? Any timely help is appreciated. Thanks in advance.

Community
  • 1
  • 1
Ananth
  • 815
  • 9
  • 26

2 Answers2

0

Are you sure your webpage does load the jQuery library (from disk or online)?

You can debug the webview with safari to check what's going wrong when the webview is open in the simulator or on your device. Here's a guide from apple to get you started.

Tieme
  • 62,602
  • 20
  • 102
  • 156
0

I had the same problem. You need some different function with explicitly making HTMLImageElement and .toString() at the end of getPalette. Also there is some strange Safari behaviour, it works only with second shot:

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
simd
  • 1,779
  • 3
  • 17
  • 23