ขั้นแรก จะต้องติดตั้ง Library ให้กับ Python ก่อน โดยใส่คำสั่งดังนี้
Code: Select all
pip3 install Pillow
เปิดโปรแกรมขึ้นมา จากนั้นให้เขียน code เพื่อ import library ที่ติดตั้งมา
Code: Select all
import PIL
from PIL import Image
Code: Select all
img = Image.open( 'image MINDPHP.png' )
Code: Select all
x, y, width , height = 100, 110, 400, 180
cropped = img.crop( ( x, y , width , height ) )
print ("Crop Finish")
x = หมายถึง แกน X (แนวนอน) เลือกจุดเริ่มต้นส่วนที่ต้องการ
เช่น ขนาดกว้างทั้งหมด 0-500 pixel ส่วนที่ต้องการ คือ 100 ทำให้ pixel 0-99 เป็นส่วนที่ต้องตัดออก
y = หมายถึง แกน Y (แนวตั้ง') เลือกจุดเริ่มต้นส่วนที่ต้องการ
เช่น ขนาดสูงทั้งหมด 0-280 pixel ส่วนที่ต้องการ คือ 110 ทำให้ pixel 0-109 เป็นส่วนที่ต้องตัดออก
width = หมายถึง ความกว้างสิ้นสุด ในส่วนที่ต้องการเลือก
เช่น ขนาดกว้างทั้งหมด 100-500 pixel ส่วนที่ต้องการ คือ 400 ทำให้ pixel 401-500 เป็นส่วนที่ต้องตัดออก
height = หมายถึง ความสูงสิ้นสุด ในส่วนที่ต้องการเลือก
เช่น ขนาดสูงทั้งหมด 110-280 pixel ส่วนที่ต้องการ คือ 180 ทำให้ pixel 181-280 เป็นส่วนที่ต้องตัดออก
ในส่วนสุดท้ายเป็นการ save รูปภาพในชื่อ "New image crop.png" (หรือจะ Save ทับรูปเดิมโดยใส่ชื่อเหมือนเดิมก็ได้)
Code: Select all
cropped.save('New image crop.png')
หลัง Run โปรแกรม (จะได้ไฟล์รูปภาพเพิ่มมา 1 ไฟล์ชื่อ "New image crop.png" )
ผลลัพท์ที่ได้
Code ตัวอย่างทั้งหมด
Code: Select all
import PIL
from PIL import Image
img = Image.open( 'image MINDPHP.png' ) # size: 184 x 184
x, y , width , height = 100, 110, 400, 180
#cropped = img.crop( ( x, y, x + width , y + height ) )
cropped = img.crop( ( x, y , width , height ) )
print ("Crop Finish")
cropped.save('New image crop.png')