如何在Python 3中将QImage(QPixmap)转换为PIL图像?

时间:2017-11-14 15:47:55

标签: python pyqt pyqt4 python-imaging-library pyqt5

我想将图像从QImage或Qpixmap类转换为PIL图像。 我发现了这个:Convert PyQt to PIL image

但它似乎在Python3中不起作用。对Pyhton3实现这个方法还是更简单地使用新方法呢?

1 个答案:

答案 0 :(得分:1)

根据docs

  

StringIO和cStringIO模块消失了。相反,导入io   模块并使用io.StringIO或io.BytesIO来处理文本和数据   分别

因此,解决方案是将// create the Inventory grid var InventoryWidth = 2; var InventoryHeight = 4; var Inventory = new Array(InventoryWidth); for (var i = 0; i < InventoryWidth; i++) { Inventory[i] = new Array(InventoryHeight); } // set the Items & default quantities Inventory[0][0] = "Potion"; Inventory[1][0] = 2; Inventory[0][1] = "Elixir"; Inventory[1][1] = 9; Inventory[0][2] = "Antidote"; Inventory[1][2] = 5; Inventory[0][3] = "Ether"; Inventory[1][3] = 1; // function for sorting items function Sort2D(array2D, byColumn, ascending) { // sort, seems I am using the wrong sorting function or my approach is wrong here: // not sure how to do ASC/DESC as well array2D.sort(function(a, b) { if(a[0] === b[0]) { var x = a[byColumn].toLowerCase(), y = b[byColumn].toLowerCase(); return x < y ? -1 : x > y ? 1 : 0; } return a[0] - b[0]; }); } // sort all rows by first column: "name", setting to 1 should compare and sort the quantities instead Sort2D( Inventory, 0, true); // print grid contents var output = ""; for(var i = 0; i < InventoryHeight; i++) { if (i == 0) { output += " | name | own |"; } for(var j = 0; j < InventoryWidth; j++) { if (j == 0) { output += "\n"+i+"|"; } output+=Inventory[j][i]; if (j >= Inventory[0].length-1) { output += "|\n"; } else { output += ", "; } } } console.log(output);转换为cStringIO.StringIO

PyQt5:

io.BytesIO

PyQt4的:

import io
from PIL import Image
from PyQt5.QtGui import QImage
from PyQt5.QtCore import QBuffer

img = QImage("image.png")
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
img.save(buffer, "PNG")
pil_im = Image.open(io.BytesIO(buffer.data()))
pil_im.show()