修剪函数 Jython JES

1 投票
1 回答
3704 浏览
提问于 2025-04-17 19:51

你好,我正在Jython学生环境中尝试制作一个裁剪功能,这是我目前的进展。

我还在想办法如何让画布的大小适应所有新像素的占用。

有没有人能帮帮我?

def crop(pic, startX, endX, startY, endY):
    canvas = makeEmptyPicture(500, 800)
    for sourceX in range(startX, endX):
        for sourceY in range(startY, endY):
            color = getColor(getPixel(pic, sourceX, sourceY))
            setColor(getPixel(canvas, startX, startY), color)
            startY = startY + 1
        startX = startX + 1
    show(canvas)

1 个回答

1

试试这个:

注意:得到的画布大小可以通过(endX - startX) x (endY - startY)来计算

def crop(pic, startX, endX, startY, endY):  
    # Check if the cropping bounds are OK with size of the original picture 
    if (endX - startX > 0) and (endY - startY > 0) and \
                         (endX < getWidth(pic)) and (endY < getHeight(pic)):
        # Create a canvas with correct size
        canvas = makeEmptyPicture(endX - startX, endY - startY)
        # Browse the interesting part
        for sourceX in range(startX, endX):
            for sourceY in range(startY, endY):
                color = getColor(getPixel(pic, sourceX, sourceY))
                # Write the pixels, 
                # starting from 0 (=startX(Y)-startX(Y)) to endX(Y)
                setColor(getPixel(canvas, 
                              sourceX - startX, sourceY - startY), color)
        return canvas
    else:
        # Print error when passing wrong bounds
        printNow("Error: bad cropping bounds ! - Expected [0.." + 
            str(getWidth(pic)-1) + "] x [0.." +  str(getHeight(pic)-1) + "]")        
        return None

def main():
  file = pickAFile()
  picture = makePicture(file)
  cropPic = crop(picture, 50, 150, 50, 180)
  if (cropPic):
      show(cropPic)

main()


结果是:




...........在这里输入图片描述....................................................在这里输入图片描述...........



使用错误参数的输出:

>>> cropPic = crop(picture, 50, 500, 50, 180)
>>> 
======= Loading Progam =======
Error: bad cropping bounds ! - Expected [0..258] x [0..193]

撰写回答