python图片处理(入门一)

版权声明:本博客内容为原创,若要转载,请注明出处!否则禁止转载! https://blog.csdn.net/wardenjohn/article/details/80397353

先上一个代码例子

from PIL import Image
import os,sys

for infile in sys.argv[1:]:#
    print(infile)
    outfile=os.path.splitext(infile)[0]#os.path.splitext(text)是那infile字符串里面的按照名字和拓展名分开的方法
    print(outfile)#出现的outfile就是和拓展名分开的
    outfile+=".png"#把没有拓展名的添上我们希望的拓展名,python会自动转换格式
    print(outfile)
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)#使用Image先打开这个图片,然后用save方法保存
        except IOError:
            print("Error")

这里面我都主要的都注释了,主要看看注释

看看运行结果:

***MacBook-Pro:pyui zhangyongde$ python pic.py /Users/zhangyongde/Desktop/test.jpg
/Users/***/Desktop/test.jpg
/Users/***/Desktop/test
/Users/***/Desktop/test.png

但是如果来源不是标准的拓展的格式的时候,试试下面的方法:

import os, sys
  import Image
#create jpeg thumbnails
  for infile in sys.argv[1:]:
      outfile = os.path.splitext(infile)[0] + ".thumbnail"
      if infile != outfile:
          try:
              im = Image.open(infile)
              im.thumbnail((128, 128))
              im.save(outfile, "JPEG")#调用Save方法
          except IOError:
              print "cannot create thumbnail for", infile

但是这个库不是负责解码的。当你打开一个图片的时候,那么这个时候就会读取他的文件头并且从文件头来决定读入的格式

看看下面这个介绍:

It is important to note is that the library doesn't decode or load the raster data unless itreally has to. When you open a file, the file header is read to determine the file formatand extract things like mode, size, and other properties required to decode the file, butthe rest of the file is not processed until later. 


使用crop方法可以截取图片的一部分出来:

for infile in sys.argv[1:]:
    try:
        im=Image.open(infile)
        print(infile,im.format,"%dx%d"%im.size,im.mode)
    except IOError:
        print("Error")

box=(100,100,400,400)
region=im.crop(box)
print(region)
region.show()

看看效果


这个是原图

我们来看看运行后show的结果


这个就是给定一个元组,然后作为参数传给crop方法来截取元组内给定的部分,得到的图是300X300的图像

 region = region.transpose(Image.ROTATE_180)
      im.paste(region, box)

这个就是把得到的结果反转180度

同时把这个效果粘贴到原图像上面去

得到下面这样的结果:




猜你喜欢

转载自blog.csdn.net/wardenjohn/article/details/80397353
今日推荐