您的位置:首页 > 编程语言 > Python开发

[Python]croppic 裁剪图片的Python后台实现

2015-12-24 19:13 603 查看
import cStringIO
import io
import base64
from PIL import Image, ImageTk
def img_crop_to_file(request):
#获取文件
img_data = request.POST.get('imgUrl')
ext = img_data.split('base64,')[0].split('/')[1].split(';')[0]
img_data = img_data.split('base64,')[1]
imgData = base64.b64decode(img_data)

data_stream = cStringIO.StringIO()
data_stream.write(imgData)
source_image = Image.open(data_stream)

#原始尺寸
imgInitW = request.POST.get('imgInitW')
imgInitH = request.POST.get('imgInitH')
imgInitW,imgInitH = int(imgInitW),int(imgInitH)

#调成后尺寸
imgW = request.POST.get('imgW')
imgH = request.POST.get('imgH')
imgW,imgH = int(imgW),int(imgH)

#偏移量
imgY1 = request.POST.get('imgY1')
imgX1 = request.POST.get('imgX1')
imgY1,imgX1 = int(imgY1),int(imgX1)

#裁剪框
cropW = request.POST.get('cropW')
cropH = request.POST.get('cropH')
cropW,cropH = int(cropW),int(cropH)

#旋转角度
angle = request.POST.get('rotation')
angle = int(angle)

#创建新的图片
source_image = source_image.resize((imgW,imgH))

rotated_image = source_image.rotate(-float(angle))

rotated_width,rotated_height = rotated_image.size

dx = rotated_width - imgW
dy = rotated_height - imgH

cropped_rotated_image = Image.new('RGBA',(int(imgW),int(imgH)),0)
a = rotated_image.crop((dx/2,dy/2,dx/2+imgW,dy/2+imgH))
a.save('crop.jpeg')
cropped_rotated_image.paste(rotated_image.crop((dx/2,dy/2,dx/2+imgW,dy/2+imgH)),(0,0,imgW,imgH))

final_image = Image.new('RGBA',(int(cropW),int(cropH)),0)
final_image.paste(cropped_rotated_image.crop((imgX1,imgY1,imgX1+cropW,imgY1+cropH)),(0,0,cropW,cropH))

filename = str(uuid.uuid1())
uuidname = '%s.%s' % (filename,ext)
output_filename = os.path.join(os.path.join(MEDIA_ROOT,'images/topic_covers_processed/'),uuidname)
print(output_filename)
final_image.save(output_filename)
return HttpResponse(json.dumps({'status':'success','url':'/pics/images/topic_covers_processed/%s' % uuidname}))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: