PIL图像大小调整脚本-某些图像尺寸无法正确缩放

时间:2019-01-25 19:18:03

标签: python python-imaging-library

对于工作,我必须调整数百个图像的大小以适合830x1000像素的画布,同时保持宽高比(这样图像就不会拉伸和变形)。我使用PIL编写了python脚本。这适用于大多数图像,但是运行脚本后某些图像尺寸会失真。

我知道问题出在案情陈述中,但我不确定其确切位置。

def resize(): 
    openFiles = glob.glob('*.jpg')

    for files in openFiles:
        inFile = Image.open(files)
        fileName = os.path.splitext(files)[0] # gets filename
        outFile = fileName + ".jpg"
        print (fileName)
        print ("Original size ",inFile.size)
        xDim = inFile.size[0]
        yDim = inFile.size[1]        
        newSize = aspectRatio(xDim, yDim)       
        inFile = inFile.resize((int(newSize[0]),int(newSize[1])),Image.ANTIALIAS)
        inFile.save(outFile)
        print ("New Size ",inFile.size, "\n")

    return None


def aspectRatio(xDim, yDim):
    Ratio = float(xDim/yDim)
    xDelta = 830 - xDim
    yDelta = 1000 - yDim
    Oddball = [.99, .98, .97, .96, .95, .94, .93, .92, .91, .90, .89, .88, .87, .86, .85, .84, .83, .82, .81, .80]

    New1 = [xDim+xDelta, yDim+xDelta*Ratio]
    New2 = [xDim+yDelta*Ratio, yDim+yDelta]   

    if xDim == 830 and yDim == 1000:
        print('No Change Needed')
        return(xDim, yDim)

    if xDim == yDim:
       xDim = 830
       yDim = 830
       return(xDim, yDim)

    else:    
      if New1[0] == 830 and New1[1] <= 1000:
        xDim = float(New1[0])
        yDim = float(New1[1])
        return(xDim, yDim)

      elif New1[0] <= 830 and New1[1] <= 1000:
        xDim = float(New1[0])
        yDim = float(New1[1])
        return(xDim, yDim)

      elif New2[0] <= 830 and New2[1] ==1000:
        xDim = float(New2[0])
        yDim = float(New2[1])
        return(xDim, yDim)

      elif .83 < Ratio < 1:
        i = 0
        while xDim >= 830 and yDim >= 1000:  
          xDim = float(New2[0] * Oddball[i])
          yDim = float(New2[1] * Oddball[i])
          i =+ 1
          return(xDim,yDim)

        else:    
         print('Manual Change Required')
         return(xDim, yDim)

以下图像尺寸是当前给我带来麻烦的图像。

原始尺寸(220、643) 新尺寸(830,851)

原始尺寸(440、617) 新尺寸(830,895)

原始尺寸(597、480) 新尺寸(830,769)

原始大小(308,631) 新尺寸(830,885)

原始尺寸(450、625) 新尺寸(830,898)

原始大小(398,631) 新尺寸(830,903)

原始尺寸(220、643) 新尺寸(830,851)

原始大小(240、643) 新尺寸(830,863)

1 个答案:

答案 0 :(得分:0)

IMO,有一种更简便的方法来实现AspectRatio()

fixed_ratio = 1000 / 830.0

def aspectRatio():
    curr_ratio = yDim *1.0 / xDim
    if curr_ratio <= fixed_ratio:
        return (830, 830 * curr_ratio)
    else:
        return (1000 / curr_ratio, 1000)

这解决了您的问题。