Python在照片上添加水印的方法
from PIL import Image
def watermark_photo ( input_image_path, watermark_image_path, output_image_path) :
base_image = Image. open ( input_image_path)
watermark = Image. open ( watermark_image_path) . convert( "RGBA" )
position = base_image. size
newsize = ( int ( position[ 0 ] * 8 / 100 ) , int ( position[ 0 ] * 8 / 100 ) )
watermark = watermark. resize( newsize)
new_position = position[ 0 ] - newsize[ 0 ] - 20 , position[ 1 ] - newsize[ 1 ] - 20
transparent = Image. new( mode= 'RGBA' , size= position, color= ( 0 , 0 , 0 , 0 ) )
transparent. paste( base_image, ( 0 , 0 ) )
transparent. paste( watermark, new_position, watermark)
image_mode = base_image. mode
if image_mode == 'RGB' :
transparent = transparent. convert( image_mode)
else :
transparent = transparent. convert( 'P' )
transparent. save( output_image_path, optimize= True , quality= 100 )
watermark_photo( "文字.jpg" , "条形码.jpg" , "11111.png" )
生成的效果图,即在右下角添加了一个水印
涉及到的图片模式有如下几种:
模式
------------------------------------------------
1 1 位像素,黑和白,存成8位的像素
L 8 位像素,黑白
P 8 位像素,使用调色板映射到任何其他模式
RGB 3 ×8位像素,真彩
RGBA 4 ×8位像素,真彩+透明通道
CMYK 4 ×8位像素,颜色隔离
YCbCr 3 ×8位像素,彩色视频格式
I 32 位整型像素
F 32 位浮点型像素