【问题标题】:Pillow resize pixelating images - Django/Pillow枕头调整像素化图像的大小 - Django/Pillow
【发布时间】:2014-07-18 06:35:07
【问题描述】:

我正在用 Django 开发一个图像上传器。图像上传并保存到磁盘后, 我正在尝试调整保存图像的大小,同时保持其纵横比。我正在使用 Pillow 进行图像处理/调整大小。当我尝试调整图像大小时会出现问题,即使调整后的图像的纵横比与原始图像的纵横比相同,它也会变得像素化。

原始保存图像: https://www.dropbox.com/s/80yk6tnwt3xnoun/babu_980604.jpeg

调整大小的像素化图像: https://www.dropbox.com/s/bznodpk4t4xlyqp/babu_736302.large.jpeg

我已经尝试在谷歌上搜索这个问题,并查看了 stackoverflow 上的其他相关链接,

喜欢

How do I resize an image using PIL and maintain its aspect ratio?

Resize image maintaining aspect ratio AND making portrait and landscape images exact same size?

但问题仍然存在。

版本:

Django=1.6.4

枕头=2.4.0

virtualenv 中的一切都已设置完毕。请帮忙!

PS : 我是 Python/Django 世界的新手

这是我的代码 sn-p:

import json
import os
import hashlib
from datetime import datetime
from operator import itemgetter
import random
from random import randint
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.http import (HttpResponse, HttpResponseRedirect)
from django.core.context_processors import csrf
from django.core.files.images import get_image_dimensions
from django.shortcuts import render, redirect
from django.forms.models import model_to_dict
from django.views.decorators.csrf import csrf_exempt
from PIL import Image, ImageOps
from django.views.decorators.csrf import csrf_exempt, csrf_protect
import settings

from hashlib import md5
from django import forms

from beardedavenger.models import *

from django.views.decorators.http import require_POST

import pdb
import requests

def imagehandler(requests):
if requests.method == 'POST':
    filename = requests.FILES['file'].name
    file_extension = filename.split('.')[len(filename.split('.')) - 1].lower()
    errors = []

    username = 'nit'

    global random

    #allowed image types are png, jpg, jpeg, gif
    if file_extension not in settings.IMAGE_FILE_TYPES:
        errors.append('The image file you provided is not valid. Only the following extensions are allowed: %s' % ', '.join(settings.IMAGE_FILE_TYPES))
    else:
        image = requests.FILES['file']
        image_w, image_h = get_image_dimensions(image)
        rand = str(random.randint(100000,999999))
        with open(settings.MEDIA_ROOT + username + '_' + rand + '.jpeg', 'wb+') as destination:
            for chunk in requests.FILES['file'].chunks():
                destination.write(chunk)

        large_size = (1920, 1200)

        infile = settings.MEDIA_ROOT + username + '_' + rand + ".jpeg"

        large_file = settings.MEDIA_ROOT + username + '_' + rand +".large"

        try:
            im = Image.open(infile)

            base_width = large_size[0]

            aspect_ratio = float(image_w / float(image_h))
            new_height = int(base_width / aspect_ratio)

            if new_height < 1200:
                final_width = base_width
                final_height = new_height
            else:
                final_width = int(aspect_ratio * large_size[1])
                final_height = large_size[1]

            final_size = (final_width, final_height)

            imaged = im.resize((final_width, final_height), Image.ANTIALIAS)
            # imaged = ImageOps.fit(im, final_size, Image.ANTIALIAS, centering = (0.5,0.5))
            imaged.save(large_file, "JPEG", quality=90)

        except IOError:
            errors.append('error while resizing image')

    if not errors:
        response = HttpResponse(json.dumps({'status': 'success','filename': filename }),
        mimetype="application/json")
    else:
        response = HttpResponse(json.dumps({'status': 'failure','errors': errors,'message': 'Error uploading Picture. '}),
        mimetype="application/json")
    return response
else:
    return render(requests, 'upload.html')

更新:

我使用 Pillow 来调整和压缩我的图像。即使保持了纵横比,在调整大小时图像中也会出现一定程度的暗淡[与原始图像相比,抗锯齿比所需的更多]。我将处理库切换到 ImageMagick(反对许多建议不要这样做的帖子!)以及 Wand API(docs.wand-py.org/en/0.3.7/index.html),以处理我的图像。这种变化就像一个魅力!

【问题讨论】:

标签: python django image python-imaging-library pillow


【解决方案1】:

通过这段代码,我得到了这张没有像素化的图像(Python 2.7,Pillow 2.4.0)。

from PIL import Image

large_size = (1920, 1200)

im = Image.open("babu_980604.jpeg")

image_w, image_h = im.size
aspect_ratio = image_w / float(image_h)
new_height = int(large_size[0] / aspect_ratio)

if new_height < 1200:
    final_width = large_size[0]
    final_height = new_height
else:
    final_width = int(aspect_ratio * large_size[1])
    final_height = large_size[1]

imaged = im.resize((final_width, final_height), Image.ANTIALIAS)

imaged.show()
imaged.save("out.jpg", quality=90)

这与您的代码之间的主要区别在于它直接从打开的图像中获取image_wimage_h,而不是get_image_dimensions(image),其实现未显示。

代码中的一些小问题:

  • 您可以在with open(...) 之前设置infile 并在那里使用它。

  • final_size 未使用,可以删除,或者在im.resize() 中使用。

  • base_width 可以替换为large_size[0],因为您也可以在其他地方使用large_size[1]

  • image 设置为requests.FILES['file'],但您也可以直接使用requests.FILES['file']。你可以重复使用image

  • global random 可能不需要。

【讨论】:

  • 非常感谢!它现在可以工作了!我修复了您指出的代码中的小缺陷。但是当我调整图像大小时,我看到色调发生了变化。原始图像中有更多的蓝色,而调整大小的图像更更绿。如果您可以查看此link,那就太好了,它是原始图像和调整后的图像彼此相邻放置的屏幕截图。我该怎么做才能使色调不改变/不那么明显? link
  • 我可以看到并排图片的差异,但我不确定是什么原因造成的。有趣的是,您上传的原件看起来也是绿色而不是蓝色:dropbox.com/s/80yk6tnwt3xnoun/babu_980604.jpeg 我转换的那个也是:i.stack.imgur.com/nw9rE.jpg
  • 只是想进行更新,我正在使用 Pillow 来调整和压缩我的图像。即使保持了纵横比,在调整大小时图像中也会出现一定程度的暗淡[与原始图像相比,抗锯齿比要求的要多]。我将我的处理库切换到 ImageMagick(反对许多建议不要这样做的帖子!)以及 Wand API (docs.wand-py.org/en/0.3.7/index.html),以处理我的图像。这种变化就像一个魅力!
  • 请注意,Pillow 在 v2.7.0 中添加了 Image.thumbnail(...) 调用,这使得这更加简单。 pillow.readthedocs.org/reference/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 2012-10-08
相关资源
最近更新 更多