본문 바로가기
Python and Django

PIL을 이용한 이미지 편집 part.1

by leo21c 2012. 9. 5.
SMALL

1. open
 - Image.open(infile)
 - Image.open(infile, mode) //특정 mode로 이미지를 열수 있음.

ex)

Image.open("test.jpg", "RGB")
Image.open("test.jpg", "RGBA")

mode: 1(1-bit), L(8-bit / B&W), P(8-bit / mapped to any other palette), RGB, RGBA,  
          CMYK, YCbCr, I, F


2. new
 - Image.new(mode, size)
 - Image.new(mode, size, color)

  ex) 

from PIL import Image
im = Image.open("test.png")
size = (180, 180)
im2 = Image.new("RGBA", size)    // mode가 "RGBA" size 180 x 180 이미지 생성
im3 = Image.new("RGBA", im.size) // im 이미지와 같은 크기 


3. roate

>>> from PIL import Image
>>> im = Image.open("test.png")
>>> im2 = im.rotate(45)
>>> print im.size, im2.size
(500, 500) (500, 500)
>>> im2.save("test45.png")

  Returns a copy of an image rotated the given number of degrees counter clockwise around its center.
  rotate을 하면 이미지 크기가 변경되지 않고 이미지의 중심을 기준으로 회전한다. 따라서 이미지를 저장해 보면 상하좌우가 모두 잘려 있는 상태가 된다.
  이미지를 유지 한 상태로 회전하기 위해서는 이미지 크기를 변경한 후에 회전을 해야 한다.

4. crop

>>> from PIL import Image
>>> im = Image.open("test.png")
>>> box = (100, 100, 200, 200)
>>> im2 = im.crop(box)
>>>print im.size, im2.size
(500, 500) (100, 100)


5. load

>>>from PIL imort Image
>>> im = Image.open("test.png")
>>> print im.size
(500, 500)
>>> pix = im.load()
>>> for x in range(200,300):
          for y in range(200,300):
             pix[x, y] = (0,0,0,0)
>>> im.save("test2.png")

  load는 image의 pixel 정보를 접근할 수 있도록 해주는 함수이다.  getpixel 함수가 있지만 속도가 느리기 때문에 load를 사용하라고 권하고 있다.
  위 예제는 W 500, H 500 크기의 이미지에서 box = (200, 200, 300, 300) 크기의 pixel 색을 검게 그리고 투명하게 처리하는 것이다.

6. paste

>>> box = (100, 100)
>>> im.paste(src_img, box)

 


 - im.paste(image, box)
 The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None(same as(0,0)). If a 4-tuple is given, the size of the pasted image must match the size of the region.



LIST