在Jython/Python中复制图片时,如何使用

2024-09-28 20:54:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Jython编写一个代码,它会将一张图片的一部分复制到一张空图片中,但是我希望它在下一行复制(比方说)少10个像素。我觉得我说不通,让我举个例子来解释。一张100像素×100像素的图片,程序会将第一行(100像素)的像素复制到新图片中,但对于第二行像素,我希望它只复制90像素,然后对第三行复制80像素,依此类推。

这里我有一个代码可以复制一张图片的一部分,但是它复制一个正方形。所以我该怎么做才能让它做我想做的。我想我应该用for x in range做点什么,但我不知道。

def copyPic():
  file=pickAFile()
  oldPic=makePicture(file)
  newPic=makeEmptyPicture(getWidth(oldPic),getHeight(oldPic))
  xstart=getWidth(oldPic)/2
  ystart=getHeight(oldPic)/2
    for y in range(ystart,getHeight(oldPic)):
       for x in range(xstart, (getWidth(oldPic))):
         oldPixel=getPixel(oldPic,x,y)
         colour=getColor(oldPixel)
         newPixel=getPixel(newPic,x,y)
         setColor(newPixel,colour)
  explore(newPic)

Tags: 代码infor图片range像素filegetwidth
2条回答

混淆QR扫描器的一个简单方法是用随机单元替换代码的三个定位方块。这是对image3.png的操作,它是最小形式的。您的函数addSquares(smallPic)将添加三个定位正方形,以及将它们与活动单元格分隔开的白细胞。然后fixCodes()将展开结果图像并保存它。

你的代码看起来肯定会复制图片右下1/4。。。为了制作一个三角形的部分(或者只是一个有一个角度的部分,如果我理解你的问题正确)你需要减少X最大值每次通过。。。类似于:

def copyPic():
  file=pickAFile()
  oldPic=makePicture(file)
  newPic=makeEmptyPicture(getWidth(oldPic),getHeight(oldPic))
  xstart=getWidth(oldPic)/2
  ystart=getHeight(oldPic)/2

  # The next line gets the max value x can be (width of pic)
  xmax = getWidth(oldPic)

    for y in range(ystart,getHeight(oldPic)):

       # Now loop from the middle (xstart) to the end (xmax)
       for x in range(xstart, xmax):

         oldPixel=getPixel(oldPic,x,y)
         colour=getColor(oldPixel)
         newPixel=getPixel(newPic,x,y)
         setColor(newPixel,colour)

       # Now the x-loop has finished for this line (this value of y)
       # so reduce xmax by 10 (or whatever value) ready for the next line
       xmax = xmax - 10

       # Then you should do some checking in your code to ensure
       # xmax is not < xstart... here is something crude that should work
       if xmax < xstart:
           xmax = xstart

  explore(newPic)

我想你的代码会像这样:

+------------+
|   1     2  |
|            |
|   3     4  |
|            |
+------------+

给你这个:

+-----+
|  4  |
|     |
+-----+

因为你的X环总是一样长

如图所示每次减少x,您应该得到如下结果:

+-----+
|  4 /
|  /
+-

这是不是很好的编码,我可以重写整个事情。。。但如果您只是在学习python,那么至少我对您的代码所做的修改应该能够很好地处理您已经拥有的内容,并且应该很容易理解。我希望这会有帮助,如果你需要的话,可以随时要求澄清。

干杯

附言:我看到你问了两次这个问题-你不应该问同样的问题两次,因为它会把答案分开,而且会让以后人们很难找到这样的答案。。。

相关问题 更多 >