一、需求
前端页面需要调用后端API,实现获取主要颜色json数据
二、图片效果
三、代码实现:
# Create your views here.
import os
from django.core.files.storage import default_storage
from django.http import HttpResponse, JsonResponse
from PIL import Image
from webcolors import rgb_to_hexdef test_url(request):"""测试接口"""return HttpResponse("hello world")def palette(req):colors = {}# 判断接收方式if req.method == 'POST':# 获取图片first_image = req.FILES.get("image", None)# 保存图片image_path = os.path.join('static/', 'image.jpg')default_storage.save(image_path, first_image)# 提取图片主要的十种颜色image = Image.open(image_path)small_image = image.resize((80, 80))# 图片的主要十种颜色result = small_image.convert("P", palette=Image.ADAPTIVE, colors=10)# 提取颜色palette = result.getpalette()color_counts = sorted(result.getcolors(), reverse=True)col_sum = sum([i[0] for i in color_counts])for i in range(len(color_counts)):palette_index = color_counts[i][1]ratio = color_counts[i][0] / col_sumdominant_color = palette[palette_index * 3: palette_index * 3 + 3]# rgb转化为二进制color_str = rgb_to_hex(dominant_color[:3])# key为颜色,值为所占图片的比例colors[str(color_str)] = ratio# 删除图片os.remove(image_path)return JsonResponse({"error": 0,"message": "no error","result": {"colors": colors}})else:return JsonResponse({"error": 1,"message": "method error","result": {}})
四、返回JSON数据
{"error": 0,"message": "no error","result": {"colors": {"#f5f5f5": 0.2359375,"#685648": 0.13578125,"#423933": 0.13109375,"#1f2528": 0.12265625,"#a38970": 0.11890625,"#e5dedc": 0.11421875,"#f9f8f9": 0.06,"#f5f5f4": 0.04625,"#f4f5f5": 0.02703125,"#f9f5f6": 0.008125}}
}