Pillow python прозрачный фон

Set transparency level using Python Imaging Library/Pillow

Image processing can be allowed using The Python Imaging Library or PIL. Unfortunately PIL’s last release was in 2009 and then it stopped getting updated. Luckily there were some Python techies who came along and forked PIL and named their project as Pillow. This project Pillow is the enhanced replacement of PIL which also supports Python 3.

Note :- You cannot have both PIL and Pillow installed at the same time.

Install pillow

Transparency level –

Transparency level determines how much transparent and opaque the pixels of an image could get. An alpha channel of an image represents its transparency.

  • When the value of alpha channel of one image is 0 and of another image is 1, only the second image will be displayed since its pixels are opaque.
  • When the value of alpha channel of one image is 1 and of another image is 0, only the first image will be displayed as the pixels of the first image are opaque.
  • When alpha channels of both the images are opaque, both the pixels are to be displayed – Transparency levels are determined by the color of the pixels from both the images equally.

code –

from PIL import Image def changeImageSize(maxWidth, maxHeight, image): widthRatio = maxWidth/image.size[0] heightRatio = maxHeight/image.size[1] newWidth = int(widthRatio*image.size[0]) newHeight = int(heightRatio*image.size[1]) newImage = image.resize((newWidth, newHeight)) return newImage image1 = Image.open("./Space.png") #path of first image image2 = Image.open("./Universe.png") #path of second image image1 = changeImageSize(3290, 1300, image1) image2 = changeImageSize(3290, 1300, image2) alphaBlended = Image.blend(image1, image2, alpha=.3) alphaBlended.show()

output –

Conclusion –

As you can see, it is pretty easy and simple to use this library for adjusting the transparency at multiple levels. This library is widely used out there in the wild, make sure you master it.

Читайте также:  Php replace class name

Источник

Create transparent png image with Python, Pillow (putalpha)

Image module of the Python image processing library Pillow (PIL) provides putalpha() for adding an alpha channel to an image.

This article describes the following contents.

  • How to use Image.putalpha()
  • Set uniform transparency over the entire surface
  • Create an alpha channel with ImageDraw
  • Use the existing image as an alpha channel

Please refer to the following article for the installation and basic usage of Pillow (PIL).

Import Image from PIL and load the original image.

ImageDraw and ImageFilter are used to draw shapes and create alpha channels. They may be omitted if the image file is read and used as an alpha channel.

from PIL import Image, ImageDraw, ImageFilter im_rgb = Image.open('data/src/lena.jpg') 

lena

How to use Image.putalpha()

The parameter of putalpha() is only alpha . As it is literally put the alpha channel layer to the original image.

If mode of the original image is RGB (8 bit x 3: full color) or L (8 bit x 1: black and white), an alpha channel is newly added, and if RGBA or LA , the original alpha channel is updated.

Specified by a constant

When an integer value of 8 bits ( 0 to 255 ) is set to alpha , the transmittance according to the value is set on the entire surface.

0 means 100% transparency, 255 means 0% transparency (no transparency).

Specified by Image object

If you set an Image object of the same size as the original image in mode=’L’ (8-bit grayscale) to alpha , you can set the alpha channel to various shapes.

As in the constant case, 0 means 100% transparency, 255 means 0% transparency (no transparency).

Set uniform transparency over the entire surface

If you set an integer value to alpha, the transparency according to the value will be set on the entire surface.

Note that putalpha() overwrites the original image, so if you want to keep the original image as it is, use the one copied with copy() .

im_rgba = im_rgb.copy() im_rgba.putalpha(128) im_rgba.save('data/dst/pillow_putalpha_solid.png') 

Python Pillow putalpha solid

In this example, alpha=128 gives about 50% transparency (128 / 255 ~ 50%).

Читайте также:  Sort list method python

Create an alpha channel with ImageDraw

If you want to add an alpha channel with a simple shape, such as a circle or rectangle, drawing in the ImageDraw module is useful. For details on drawing, see the following article. You can also draw polygons.

Draw a white circle on a black background and set it to the alpha channel.

im_a = Image.new("L", im_rgb.size, 0) draw = ImageDraw.Draw(im_a) draw.ellipse((140, 50, 260, 170), fill=255) 

Python Pillow alpha circle

im_rgba = im_rgb.copy() im_rgba.putalpha(im_a) im_rgba_crop = im_rgba.crop((140, 50, 260, 170)) im_rgba_crop.save('data/dst/pillow_putalpha_circle.png') 

Python Pillow putalpha circle

You can use ImageFilter to smooth out the boundaries.

im_a_blur = im_a.filter(ImageFilter.GaussianBlur(4)) 

Python Pillow alpha circle

im_rgba = im_rgb.copy() im_rgba.putalpha(im_a_blur) im_rgba_crop = im_rgba.crop((135, 45, 265, 175)) im_rgba_crop.save('data/dst/pillow_putalpha_circle_blur.png') 

Python Pillow putalpha circle

In each example, the outside of the circle is trimmed to a rectangle with crop() . See the following article for crop() .

Use the existing image as an alpha channel

You can load an existing image and set it as an alpha channel.

Try using a black and white horse-shaped image (scikit-image sample: skimage.data.horse()).

Python Pillow alpha horse

In this example, to leave the image horse-shaped, use an image with a white horse and a black background (an inverted image).

Python Pillow alpha horse reverse

After the image is read by open() , it is adjusted to the size of the pasted image by resize() , and the mode is converted to ‘L’ (grayscale) by convert() .

im_a = Image.open('data/src/horse_r.png').convert('L').resize(im_rgb.size) 

Python Pillow alpha horse reverse

im_rgba = im_rgb.copy() im_rgba.putalpha(im_a) im_rgba.save('data/dst/pillow_putalpha_horse.png') 

Python Pillow putalpha horse

  • Paste another image into an image with Python, Pillow
  • Composite two images according to a mask image with Python, Pillow
  • Add padding to the image with Python, Pillow
  • How to use Pillow (PIL: Python Imaging Library)
  • Resize images with Python, Pillow
  • Detect and read barcodes and QR codes with ZBar in Python
  • Concatenate images with Python, Pillow
  • Get image size (width, height) with Python, OpenCV, Pillow (PIL)
  • Get the image from the clipboard with Python, Pillow
  • Generate QR code image with Python, Pillow, qrcode
  • Python, Pillow: Flip image
  • How to create animated GIF with Pillow in Python
  • Crop a part of the image with Python, Pillow (trimming)
  • Invert image with Python, Pillow (Negative-positive inversion)
  • Draw circle, rectangle, line, etc. with Python, Pillow
Читайте также:  Php constant in interface

Источник

Изменить прозрачность картинки используя pillow

pillow переворачивает картинки
if os.stat(‘media/’+file_url).st_size> 5000000: image = Image.open(‘media/’ +.

Вывести изогнутый текст на картинку используя библиотеку pillow
Хочу вывести текст изогнутый. Например внутри круга. Как это сделать?

Как построить вписанную в треугольник окружность используя библиотеку Pillow?
Сам треугольник у меня строить получается,а вот окружность уже проблема.Как это может выглядеть?

Изменить размер у ПНГ-картинки, сохранив прозрачность
Delphi XE Суть следующая. В программе пользователи могут загружать картинки, любых размеров. Эти.

Лучший ответ

Сообщение было отмечено Ahmadenejat как решение

Решение

Много с Pillow не работал, но по запросу «Piloow alpha» нашел документацию по использованию «putalpha».
Возможно это не самый хороший вариант, но он более доступный и легкий в запоминании.
Если он вам не подходит, можете поискать по такому же запросу «putalpha».
Там много еще всяких интересных штук, по типу маск и т.п.

Пример с сайта (где 0 — минимум, а 255 — максимум):

im_rgba = im_rgb.copy() im_rgba.putalpha(128) im_rgba.save('data/dst/pillow_putalpha_solid.png')

Эксперт Python

from PIL import Image image = Image.open('image.png') image = alpha(image, 0.5)

Упс. Забыл добавить в начало:

from PIL import Image, ImageDraw, ImageFilter im_rgb = Image.open('data/src/lena.jpg')

Изменить положение картинки в Excel, не используя макросы
Можно ли изменить положение картинки в Excel, не используя макросы? Если картинку создавать как.

Прозрачность картинки
Здравствуйте. Подскажите, я загружаю картинку castle с прозрачным фоном, а фон не.

Прозрачность картинки
Нужно верхний правый угол к картинки сделать прозрачным, картинка jpg Подскажите как.

Прозрачность картинки
Надо изменить появление картинки с помощью прозрачности (чтобы появлялась и исчезала) Подскажите.

Прозрачность картинки
Как сделать так чтобы можно было регулировать прозрачность Image от 0 до 100(т.е. при нулевой.

Прозрачность картинки в JavaScript
Привет народ. Как можно убрать белые края у .bmp картинки, эта картинка в форме ромбика, а у.

Источник

Оцените статью