2012-03-27 53 views
1

我需要的是: - 有两个图像:背景(大)和图像(较小) - 在背景上有一个斜线框,我想在其中合并轮廓PIC粘贴两个文件后图像质量较差

代码:

# open the profile pic 
im = PIL.Image.open(pic) 
# resize it to dim of oblique box 
im = im.resize((picX, picY)) 

# this is the degree of oblique box 
degree = 13.67 

# open the background 
bg = PIL.Image.open(bgsrc) 
bgosize = bg.size 
bginfo = bg.info 


# first, I rotate the background to be paralell with profile pic 
bg = bg.rotate(-degree, resample = PIL.Image.BILINEAR, expand = True) 

# paste the profile pic to background 
bg.paste(im, (px1, py1, px2, py2)) 

# rotate back to original orientation 
bg = bg.rotate(degree, resample = PIL.Image.BILINEAR, expand = False) 


# crop the rotated image, because it's greater than original size, 
# after first rotate - coords are stored 
bg.crop(bgx1, bgy1, bgx2, bgy2) 

PIL.ImageFile.MAXBLOCK = bg.size[0] * bg.size[1] 
bg.save(dst, quality = 250, optimize = True, **bginfo) 

这个变换后的结果图像是nubbly一个litlebit ...

我怎样才能得到一个良好的育人质量的图像?

感谢:

a。

回答

3

提示1:使用Image.BICUBIC而不是Image.BILINEAR。不幸的是rotate不接受Image.ANTIALIAS这将提供更好的结果。提示2:不要旋转背景并稍后将其旋转,请旋转要粘贴的图像。

提示3:以'L'格式创建一个纯白色图像,并且尺寸与您粘贴的图像相同。以同样的方式旋转它。将它用作paste的掩码参数。


我没有测试过这段代码,但它应该可以工作。有一个问题, quality = 250应该完成什么?例如, JPEG options只接受1到95的值。

# open the profile pic 
im = PIL.Image.open(pic) 
# resize it to dim of oblique box 
im = im.resize((picX, picY), PIL.Image.ANTIALIAS) 

# this is the degree of oblique box 
degree = 13.67 

# open the background 
bg = PIL.Image.open(bgsrc) 
bgosize = bg.size 
bginfo = bg.info 

# create a copy of the profile that is all white 
mask = PIL.Image.new('L', im.size, 0xff) 

# rotate the profile and the mask 
im = im.rotate(degree, resample = PIL.Image.BICUBIC, expand = True) 
mask = mask.rotate(degree, resample = PIL.Image.BICUBIC, expand = True) 

# paste the profile pic to background 
bg.paste(im, (px1, py1, px2, py2), mask) 

PIL.ImageFile.MAXBLOCK = bg.size[0] * bg.size[1] 
bg.save(dst, quality = 250, optimize = True, **bginfo) 
+0

嗨马克,感谢您的回复, 1:我试过BILINEAR也是 - 它没有效果。 2:如果我首先旋转轮廓图片,它将调整到更大的尺寸,黑色背景 - 如何将JPEG转换/变换为不透明的PNG? 3:我会检查掩码参数,如果你有一个例子,我感谢你:) – airween 2012-03-27 18:19:32

+0

嗨马克,谢谢你的例子。 如果我在im.rotate和mask.rotate之后即时保存图像,那么它们也是非常重要的...因此,即使我打开背景并从PIL中保存它,它也会一目了然。 我的另一个评论:当cr对象(而不是im)被遮罩时,它具有黑色背景 - 我如何创建透明背景?非常感谢: – airween 2012-03-28 08:36:19

1

尝试双三次插值?如果没有帮助,请尝试使图像变大(例如,2倍甚至4倍大小),然后旋转,然后缩小至原始尺寸。

+0

我试过 - 没有改变。更大的图像不是解决方案,因为个人资料图片将来自用户 - 我不能(不希望)期待更大的图像。 – airween 2012-03-27 18:15:27

+0

@airween,我认为他的建议是调整大小,旋转,调整回原来的大小。 – 2012-03-27 18:21:11

+0

Ahm',所以,对不起,我误解了 - 好吧,我会检查出来,谢谢。 – airween 2012-03-27 18:31:13