Home > Backend Development > Python Tutorial > python处理圆角图片、圆形图片的例子

python处理圆角图片、圆形图片的例子

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 11:30:04
Original
1779 people have browsed it

效果图如下:

python处理圆角图片、圆形图片的例子
图1(头像图片剪成圆形的,其他为透明)

python处理圆角图片、圆形图片的例子
图2(给图片的4个角加椭圆)


以前没处理过,处理起来真是有点费力呀。

用到的模块:

代码如下:


import os, math
import Image
import ImageDraw

1 头像图片剪成圆形的,其他为透明

搜索了好久,没有找到比较好的方法,有个博客(不好意思,忘记博客地址了)用了一个比较诡异的方法,我试了一下,除了处理jpg图片没有格式转换,其他的都没有问题,我当时就先按照那个方法来了

代码如下:


def circle():

    ima = Image.open("test.jpg").convert("RGBA")

    size = ima.size

    # 因为是要圆形,所以需要正方形的图片

    r2 = min(size[0], size[1])

    if size[0] != size[1]:

        ima = ima.resize((r2, r2), Image.ANTIALIAS)

    imb = Image.new('RGBA', (r2, r2),(255,255,255,0))

    pima = ima.load()

    pimb = imb.load()

    r = float(r2/2) #圆心横坐标

    for i in range(r2):

        for j in range(r2):

            lx = abs(i-r+0.5) #到圆心距离的横坐标

            ly = abs(j-r+0.5)#到圆心距离的纵坐标

            l  = pow(lx,2) + pow(ly,2)

            if l

                pimb[i,j] = pima[i,j]

    imb.save("test_circle.png")

这个方法是 计算每个像素到原点(就是图片中心点)的距离来画圆形的


2、给图片的4个角加椭圆

代码如下:


def circle_corder_image():

    im = Image.open("test.jpg").convert("RGBA")

    rad = 10  # 设置半径 

    circle = Image.new('L', (rad * 2, rad * 2), 0)

    draw = ImageDraw.Draw(circle)

    draw.ellipse((0, 0, rad * 2, rad * 2), fill=255)

    alpha = Image.new('L', im.size, 255)

    w, h = im.size

    alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))

    alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h – rad))

    alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w – rad, 0))

    alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w – rad, h – rad))

    im.putalpha(alpha)

    im.save('test_circle_corder.png')

用了这个方法后,想了一想,头像图片剪成圆形的,其他为透明,用这个方法也是可以的,于是画圆形有了下面的方法:

代码如下:


def circle_new():

    ima = Image.open("test.jpg").convert("RGBA")

    size = ima.size

    r2 = min(size[0], size[1])

    if size[0] != size[1]:

        ima = ima.resize((r2, r2), Image.ANTIALIAS)

    circle = Image.new('L', (r2, r2), 0)

    draw = ImageDraw.Draw(circle)

    draw.ellipse((0, 0, r2, r2), fill=255)

    alpha = Image.new('L', (r2, r2), 255)

    alpha.paste(circle, (0, 0))

    ima.putalpha(alpha)

    ima.save('test_circle.png')

虽然最后我想要的都有了,但是通过对这2个问题的研究,我看到了python 图片处理的强大,好多还值得我去学习研究。

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template