i want to take screenshot and crop only the captcha image, im write this code : http://pastebin.com/Hqau6kRD :
elem = driver.find_element_by_css_selector("#imagecpt")
loc = elem.location
size = elem.size
left = loc['x']
top = loc['y']
width = size['width']
height = size['height']
box = (int(left), int(top), int(left+width), int(top+height))
screenshot = driver.get_screenshot_as_png()
img = Image.open(StringIO.StringIO(screenshot))
area = img.crop(box)
area.save('screenshot.png', 'PNG')
the image saved is complete black, where im wrong ?
Yeah. For Python3 it will be like:
...
from io import BytesIO
...
screenshot = driver.get_screenshot_as_base64()
img = Image.open(BytesIO(base64.b64decode(screenshot))
...
I'm assuming you are using the Image module from PIL library.
Try getting the base64 value, decode it and then pass it as a parameter to the open() method.
...
screenshot = driver.get_screenshot_as_base64()
img = Image.open(StringIO.StringIO(base64.b64decode(screenshot))
...
Related
I have a snippet that reads my images locally (returns binary), i.e:
image = 'car.jpg'
with open(image, 'rb') as image_file:
content = image_file.read()
I'm trying to recreate the same but with images that are hosted on the internet, I have tried with the following but I've had no luck.
from urllib.request import urlopen
from PIL import Image
import io
url = 'https://somewebsite.com/fm-01/car.jpg'
image = urlopen(url)
image_file = io.BytesIO(image.read())
im = Image.open(image_file)
im = im.tobytes()
EDIT ...
Same exact image, one on google cloud storage and the other one locally.
They have different bytes when opening them.
with open('car.jpg','rb') as image_file:
content = image_file.read()
print(len(content))
size : 234712
url = 'https://storage.googleapis.com/fm-01/car.jpg'
img = Image.open(urlopen(url))
image = img.tobytes()
print(len(image))
size : 1077600
It is simple as:
from urllib.request import urlopen
url = 'https://somewebsite.com/fm-01/car.jpg'
img = urlopen(url).read()
You have not understood the comment I made explaining exactly this under Mikhail's answer.
The 234,712 bytes is the size of the JPEG-encoded data in the disk file - it includes the image height, width, date, GPS coordinates, camera manufacturer and the all the pixels of the image DCT-compressed into a JPEG.
The 1,077,600 bytes is the size of the array you will need to create in memory to hold the uncompressed red, green and blue pixels in, say 898x400 pixels at 3 bytes (1 red, 1 green and 1 blue) per pixel.
898 * 400 * 3 = 1077600
This block of code is to save the image data read from a byte array to the Image img
val = bytearray(message.msg)
size = re.split(r',', message.messageSize)
img = Image.new("L", (int(size[0]), int(size[1])), 0)
pix = img.load()
counter = 0
for y in range(int(size[1])):
for x in range(int(size[0])):
pix[x, y] = val[counter]
counter = counter + 1
Then if I img.save('test.png', 'PNG') and QPixmap('test.png'), it will display the image normally. But if I use the following method, the image would be twisted.(screenshot and image are attached to the hyperlinks below)
self.imgQ = ImageQt(img) # img is PIL Image type
img.save('test.png', 'PNG') # this will be success
pixMap = QtGui.QPixmap.fromImage(self.imgQ)
self.scene1.clear()
self.scene1.addPixmap(pixMap)
self.scene1.update()
self.viewMessage.fitInView(QRectF(0, 0, int(size[0]), int(size[1])), Qt.KeepAspectRatio)
after I implemented the code above, the image is shown twisted. But if I saved the image, the image looks correct.
[update] even if I use the PNG that I saved, it still twisted.
im = Image.open('hehe.png')
I have uploaded the PNG file here.
I am trying to generate a image which produces gif like effect by flushing the response continuously to the browser, I am relatively new to django/python and tried with following code testing for both text and image. The generator for text works fine but in case of image only first version of image is being generated.
I tried searching but can't find anything on this. I am confused how to proceed with this or if this is at all possible with django or If the idea is conceptually wrong.
Image Generator :
def refreshx():
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
size = (1000,500)
im = Image.new('RGB', size)
draw = ImageDraw.Draw(im)
red = (255,255,255)
text_pos = (10,30)
draw.text(text_pos, str(datetime.datetime.today()), fill=red)
buffer = StringIO.StringIO()
im.save(buffer, 'PNG')
yield buffer.getvalue()
time.sleep(5)
buffers = StringIO.StringIO()
ims = Image.new('RGB', size)
draws = ImageDraw.Draw(ims)
text_poss = (30,80)
draws.text(text_poss, 'dasdasdsa', fill=red)
print 'been there'
ims.save(buffers, 'PNG')
yield buffers.getvalue()
Text Generator :
def testgenerator():
yield str(datetime.datetime.today())
time.sleep(5)
yield str(datetime.datetime.today())
View Function :
def test(request):
#return HttpResponse(testgenerator());
return HttpResponse(refreshx(), mimetype="image/png")
EDIT :
I learned while researching that there's a concept called gifsocket, I'm looking into it..please suggest if anyone has experience with these
I am trying to send a webcam image to browser using Python. Now, I send it using the following code:
def send_a_frame():
capture = cv2.VideoCapture(0)
frame = capture.read()[1]
cv2.imwrite("im1.png",frame)
cnt = open("im1.png","rb").read()
b64 = base64.encodestring(cnt)
html = "<html><img src='data:image/png;base64,"+base64 +"'></html"
send(html)
How can I save an image and reopen an image and convert to base64 with a single statement?
I had the same problem, in my case I was reading from video file but it should work. Use cv2.imencode() method. See the following code
def send_a_frame():
capture = cv2.VideoCapture(0)
frame = capture.read()[1]
cnt = cv2.imencode('.png',frame)[1]
b64 = base64.encodestring(cnt)
html = "<html><img src='data:image/png;base64,"+b64 +"'></html"
send(html)
i have a problem when converting some Qimages to thumbnails using PIL.
to be used in a list widget , check the image below
where the image should look like :
please note that i use horizontal flow and the text of item is an empty text
one more thing : this only happens when i put more than 1 image
for i in listOfImages:
picture = Image.open(i)
picture.thumbnail((50,50), Image.ANTIALIAS )
qimage = QtGui.QImage(ImageQt.ImageQt(picture))
icon = QtGui.QIcon(QtGui.QPixmap.fromImage(qimage))
item = QtGui.QListWidgetItem(str(path))
item.setIcon(icon)
self.listWidget.addItem(item)
any idea what is going on ? and why images are being pixlated ?.. any better solutions
EDIT : using
pix = QtGui.QPixmap(path)
pix = pix.scaled(50,50,QtCore.Qt.KeepAspectRatio)
icon = QtGui.QIcon(pix)
will be very problematic (needed 10 seconds to run) while the code above needed 1 second.
thanks
from io import BytesIO
qimage = QtGui.QImage()
fp = BytesIO()
picture.save(fp, "BMP")
qimage.loadFromData(fp.getvalue(), "BMP")
icon ...
I had tried ImageQt, but the performance is not good.
I reference http://doloopwhile.hatenablog.com/entry/20100305/1267782841
Because I use python 3.3, cStringIO is replaced by BytesIO
I've not used PIL with PyQt. Have you tried using a QImageReader?
item = QListWidgetItem(image_path)
imageReader = QImageReader()
imageReader.setFileName(image_path)
size = imageReader.size()
size.scale(50, 50, Qt.KeepAspectRatio)
imageReader.setScaledSize(size)
image = imageReader.read()
pix = QPixmap.fromImage(image)
icon = QIcon(pix)
item.setIcon(icon)
self.listWidget.addItem(item)