찾다
백엔드 개발파이썬 튜토리얼python处理图片之PIL模块简单使用方法

本文实例讲述了python处理图片之PIL模块简单使用方法。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/env python  
#encoding: utf-8 
import Image  
class myimg: 
  def __init__(self, open_file, save_file): 
    self.img = Image.open(open_file) 
    self.save_file = save_file 
  def Change_Size(self, percent=100, height=None, width=None): 
    ''''' 
    percent:以百分比来决定大小 
    height, width:以指定的高、宽来决定大小 
    ''' 
    if not (height and width): 
      width,height = self.img.size   
    new_img = self.img.resize((width*percent/100,height*percent/100),Image.BILINEAR) 
    new_img.save(self.save_file) 
  def Rotation(self, angle): 
    ''''' 
    angle: 旋转的度数 
    ''' 
    rot_img = self.img.rotate(angle) #旋转 
    rot_img.save(self.save_file) 
  def Save_as(self, filename): 
    ''''' 
    filename: 另存为图片格式,直接根据后缀名来 
    ''' 
    self.img.save(filename)  
  def Draw_Something(self): 
    ''''' 
        利用ImageDraw来画图形 
    ''' 
    import ImageDraw 
    draw = ImageDraw.Draw(self.img) 
    width,height = self.img.size 
    draw.line(((0,0),(width-1,height-1)),fill=255) #画直线 
    draw.line(((0,height-1),(width-1,0)),fill=255) 
    draw.arc((0,0,width-1,height-1),0,360,fill=255) #画椭圆 
    self.img.save(self.save_file) 
  def Enhance_Something(self): 
    ''''' 
        利用 ImageEnhance来增强图片效果 
    ''' 
    import ImageEnhance 
    brightness = ImageEnhance.Brightness(self.img) 
    bright_img = brightness.enhance(2.0) ##亮度增强 
    bright_img.save(self.save_file) 
    sharpness = ImageEnhance.Sharpness(self.img) 
    sharp_img = sharpness.enhance(7.0) #锐度增强 
    sharp_img.save(self.save_file) 
    contrast = ImageEnhance.Contrast(self.img) #对比度增强 
    contrast_img = contrast.enhance(2.0)  
    contrast_img.save(self.save_file) 
if __name__ == "__main__": 
  file_name = r"D:\test.png" 
  save_file = r"D:\save.png" 
  saveas_file = r"D:\save_as.bmp" 
  oimg = myimg(file_name, save_file) 
  oimg.Change_Size(30) 
  oimg.Rotation(45) 
  oimg.Save_as(saveas_file) 
  oimg.Draw_Something() 
  oimg.Enhance_Something()

原图:

处理过的画图:(锐化过的)

PS:此外还有另一个比较常用的模块,image模块。

希望本文所述对大家的Python程序设计有所帮助。

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Python의 하이브리드 접근법 : 컴파일 및 해석 결합Python의 하이브리드 접근법 : 컴파일 및 해석 결합May 08, 2025 am 12:16 AM

PythonuseSahybrideactroach, combingingcompytobytecodeandingretation.1) codeiscompiledToplatform-IndependentBecode.2) bytecodeistredbythepythonvirtonmachine, enterancingefficiency andportability.

Python 's 'for'와 'whind'루프의 차이점을 배우십시오Python 's 'for'와 'whind'루프의 차이점을 배우십시오May 08, 2025 am 12:11 AM

"for"and "while"loopsare : 1) "에 대한"loopsareIdealforitertatingOverSorkNowniterations, whide2) "weekepindiTeRations.Un

Python Concatenate는 중복과 함께 목록입니다Python Concatenate는 중복과 함께 목록입니다May 08, 2025 am 12:09 AM

Python에서는 다양한 방법을 통해 목록을 연결하고 중복 요소를 관리 할 수 ​​있습니다. 1) 연산자를 사용하거나 ()을 사용하여 모든 중복 요소를 유지합니다. 2) 세트로 변환 한 다음 모든 중복 요소를 제거하기 위해 목록으로 돌아가지 만 원래 순서는 손실됩니다. 3) 루프 또는 목록 이해를 사용하여 세트를 결합하여 중복 요소를 제거하고 원래 순서를 유지하십시오.

파이썬 목록 연결 성능 ​​: 속도 비교파이썬 목록 연결 성능 ​​: 속도 비교May 08, 2025 am 12:09 AM

fastestestestedforListCancatenationInpythondSpendsonListsize : 1) Forsmalllist, OperatoriseFficient.2) ForlargerLists, list.extend () OrlistComprehensionIsfaster, withextend () morememory-efficientBymodingListsin-splace.

Python 목록에 요소를 어떻게 삽입합니까?Python 목록에 요소를 어떻게 삽입합니까?May 08, 2025 am 12:07 AM

toInsertElmentsIntoapyThonList, useAppend () toaddtotheend, insert () foraspecificposition, andextend () andextend () formultipleElements.1) useappend () foraddingsingleitemstotheend.2) useinsert () toaddatespecificindex, 그러나)

Python은 후드 아래에 동적 배열 또는 링크 된 목록이 있습니까?Python은 후드 아래에 동적 배열 또는 링크 된 목록이 있습니까?May 07, 2025 am 12:16 AM

pythonlistsareimplementedesdynamicarrays, notlinkedlists.1) thearestoredIntIguousUousUousUousUousUousUousUousUousUousInSeripendExeDaccess, LeadingSpyTHOCESS, ImpactingEperformance

파이썬 목록에서 요소를 어떻게 제거합니까?파이썬 목록에서 요소를 어떻게 제거합니까?May 07, 2025 am 12:15 AM

PythonoffersfourmainmethodstoremoveElementsfromalist : 1) 제거 (값) 제거 (값) removesthefirstoccurrencefavalue, 2) pop (index) 제거 elementatAspecifiedIndex, 3) delstatemeveselementsByindexorSlice, 4) RemovesAllestemsfromTheChmetho

스크립트를 실행하려고 할 때 '허가 거부'오류가 발생하면 무엇을 확인해야합니까?스크립트를 실행하려고 할 때 '허가 거부'오류가 발생하면 무엇을 확인해야합니까?May 07, 2025 am 12:12 AM

Toresolvea "permissionDenied"오류가 발생할 때 오류가 발생합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기