1

How can I get the dominant color of an image as rgb or hexcode?

I found a script called Color Thief but it does not allow image URLs only paths.

Uri Goren
  • 13,386
  • 6
  • 58
  • 110
user1706680
  • 1,103
  • 3
  • 15
  • 34

2 Answers2

0

use urllib to download the image first, then delete the unnecessary file:

from colorthief import ColorThief
import urllib
import os
def dominant_color_from_url(url,tmp_file='tmp.jpg'):
    '''Downloads ths image file and analyzes the dominant color'''
    urllib.urlretrieve(url, tmp_file)
    color_thief = ColorThief(tmp_file)
    dominant_color = color_thief.get_color(quality=1)
    os.remove(tmp_file)
    return dominant_color
Uri Goren
  • 13,386
  • 6
  • 58
  • 110
0

If you don't want to download unnecessary file, do it this way:

# -*- coding: utf-8 -*-

import sys

if sys.version_info < (3, 0):
    from urllib2 import urlopen
else:
    from urllib.request import urlopen

import io

from colorthief import ColorThief


fd = urlopen('http://lokeshdhakar.com/projects/color-thief/img/photo1.jpg')
f = io.BytesIO(fd.read())
color_thief = ColorThief(f)
print(color_thief.get_color(quality=1))
print(color_thief.get_palette(quality=1))
Darshan Gada
  • 583
  • 5
  • 9