Adding transparency to the program written in Python

61 Views Asked by At

I found the code below from one of the posts here very useful, but would someone, please, tell me how to add an alpha channel to that?

I just need to add opacity from 0 to 100%. I know ppm file supports it and I am completely new to Python.

I tried adding the 4-th parameter as RGB(A), but it didn't work.

I need exactly a *.ppm file generated by the program below with transparency added to it.

import array
width,height = 800,600

PPMheader = 'P6\n' +str(width) + ' ' +str(height) + '\n255\n'

# Create and fill a red PPM image
image = array.array('B', [255, 0, 0] * width * height)

# Save as PPM image
with open('result.ppm', 'wb') as f:
   f.write(bytearray(PPMheader, 'ascii'))
   image.tofile(f)
1

There are 1 best solutions below

0
Mark Setchell On

The PPM image format is part of the NetPBM suite and only supports 3 RGB channels of 8/16 bits/sample data - but without any alpha/transparency channel.

There is a widely-used extension to that called PAM "Portable Arbitrary Map" which allows an alpha/transparency channel. The format is understood by many of the NetPBM tools and also by ImageMagick, e.g. you can convert a PAM image to PNG with ImageMagick using magick INPUT.PAM OUTPUT.PNG

So, I am hoping that will work for you. Here is an example:

#!/usr/bin/env python3

import numpy as np

# Define image dimension and centre in x/y directions
width,height = 800,600
cx = width//2
cy = height//2

PAMheader = f'P7\nWIDTH {width}\nHEIGHT {height}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n'

# Create and fill a fully opaque red PAM image, 4 means RGBA channels
image = np.full((height, width, 4), [255,0,0,255], np.uint8)

# Make big transparent hole in centre
image[cy-160:cy+160, cx-160:cx+160, 3] = 0

# Make slightly smaller semi-transparent hole, i.e. A channel is 128, i.e. image [:,:,3] = 128
image[cy-80:cy+80, cx-80:cx+80, 3] = 128

# Save as PAM image
with open('result.pam', 'wb') as f:
   f.write(PAMheader.encode())
   image.tofile(f)

enter image description here