Python requests base64 image - python

I am using requests to get the image from remote URL. Since the images will always be 16x16, I want to convert them to base64, so that I can embed them later to use in HTML img tag.
import requests
import base64
response = requests.get(url).content
print(response)
b = base64.b64encode(response)
src = "data:image/png;base64," + b
The output for response is:
response = b'GIF89a\x80\x00\x80\x00\xc4\x1f\x00\xff\xff\xff\x00\x00\x00\xff\x00\x00\xff\x88\x88"""\xffff\...
The HTML part is:
<img src="{{src}}"/>
But the image is not displayed.
How can I properly base-64 encode the response?

I think it's just
import base64
import requests
response = requests.get(url)
uri = ("data:" +
response.headers['Content-Type'] + ";" +
"base64," + base64.b64encode(response.content))
Assuming content-type is set.

This worked for me:
import base64
import requests
response = requests.get(url)
uri = ("data:" +
response.headers['Content-Type'] + ";" +
"base64," + base64.b64encode(response.content).decode("utf-8"))

You may use the base64 package.
import requests
import base64
response = requests.get(url).content
print(response)
b64response = base64.b64encode(response)
print b64response

Here's my code to send/receive images over Http requests, encoded with base64
Send Request:
# Read Image
image_data = cv2.imread(image_path)
# Convert numpy array To PIL image
pil_detection_img = Image.fromarray(cv2.cvtColor(img_detections, cv2.COLOR_BGR2RGB))
# Convert PIL image to bytes
buffered_detection = BytesIO()
# Save Buffered Bytes
pil_detection_img.save(buffered_detection, format='PNG')
# Base 64 encode bytes data
# result : bytes
base64_detection = base64.b64encode(buffered_detection.getvalue())
# Decode this bytes to text
# result : string (utf-8)
base64_detection = base64_detection.decode('utf-8')
base64_plate = base64_plate.decode('utf-8')
data = {
"cam_id": "10415",
"detecion_image": base64_detection,
}
Recieve Request
content = request.json
encoded_image = content['image']
decoded_image = base64.b64decode(encoded_image)
out_image = open('image_name', 'wb')
out_image.write(decoded_image)

Related

Saving a pymupdf fitz object to s3 as a pdf

I am trying to crop a pdf and save it to s3 with same name using lambda. I am getting error on the data type being a fitz.fitz.page
import os
import json
import boto3
from urllib.parse import unquote_plus
import fitz, sys
from io import BytesIO
OUTPUT_BUCKET_NAME = os.environ["OUTPUT_BUCKET_NAME"]
OUTPUT_S3_PREFIX = os.environ["OUTPUT_S3_PREFIX"]
SNS_TOPIC_ARN = os.environ["SNS_TOPIC_ARN"]
SNS_ROLE_ARN = os.environ["SNS_ROLE_ARN"]
def lambda_handler(event, context):
textract = boto3.client("textract")
if event:
file_obj = event["Records"][0]
bucketname = str(file_obj["s3"]["bucket"]["name"])
filename = unquote_plus(str(file_obj["s3"]["object"]["key"]))
doc = fitz.open()
s3 = boto3.resource('s3')
obj = s3.Object(bucketname, filename)
fs = obj.get()['Body'].read()
pdf=fitz.open("pdf", stream=BytesIO(fs))
#pdf.close()
rect=fitz.Rect(0.0, 0.0, 595.0, 842.0)
#page = pdf[0]
page1 = doc.new_page(width = rect.width, # new page with ...
height = rect.height)
page1.show_pdf_page(rect, pdf, 0)
print(type(doc))
print(type(page1))
s3.Bucket(bucketname).put_object(Key=filename, Body=page1)
This is happening because the page1 object is defined using fitz.fitz.page and the type expected by S3 put object is bytes.
In order to solve the issue, you can use the write function of the new PDF (doc) and get the output of it which is in bytes format that you could pass to S3 then.
# Save fil first.
new_bytes = doc.write()
s3.Bucket(bucketname).put_object(Key=filename, Body=new_bytes)
For some reason for me the doc.write() method didn't return a bytes object like stated above. Here's an additional way to create a new doc, convert to bytes using BytesIO, and then save it to s3 as a pdf:
import fitz
from io import BytesIO
client = boto3.client("s3")
# create new doc object
single_page = fitz.open()
# insert a page from original_pdf_doc
single_page.insert_pdf(
original_pdf_doc, from_page=from_page_num, to_page=to_page_num
)
# Use BytesIO and .write() method to save to a bytes object
bytes_ = BytesIO(single_page.write())
# Upload the bytes object!
client.put_object(Body=bytes_, Bucket=bucket, Key=key)

Have an image link from iMDB api, how can I change it's size pyton

I am trying to work with IMDb API. My code thus far is
import http.client
import json
import requests
conn = http.client.HTTPSConnection("imdb-api.com", 443)
payload = ''
headers = {'User-agent': 'Chrome/95.0'}
conn.request("GET", "https://imdb-api.com/en/API/MostPopularMovies/<API_Key>",headers=headers)
res = conn.getresponse()
data = res.read()
convertedDict = json.loads(data.decode("utf-8"))
imagepath = r'venv/files/image.jpeg'
req = requests.get(convertedDict['items'][0]['image'], headers=headers)
with open(imagepath, 'wb') as file:
file.write(req.content)
This allows me to download the image of the first popular movie, however, the image size is really small. This is the link that I am downloading. I know that if I get rid of everything after # the image will become a lot larger. Is there a way to edit the link such that I can drop everything after # and even edit the numbers after UX with code?
Everything I try to do with string or URL operations give's me an error
https://m.media-amazon.com/images/M/MV5BZWMyYzFjYTYtNTRjYi00OGExLWE2YzgtOGRmYjAxZTU3NzBiXkEyXkFqcGdeQXVyMzQ0MzA0NTM#._V1_UX128_CR0,3,128,176_AL_.jpg
Thank you in advance
Explanation
(code example below)
Here's how to get a bigger image of the size you want. Given this URL,
https://m.media-amazon.com/images/M/MV5BZWMyYzFjYTYtNTRjYi00OGExLWE2YzgtOGRmYjAxZTU3NzBiXkEyXkFqcGdeQXVyMzQ0MzA0NTM#._V1_UX128_CR0,3,128,176_AL_.jpg
There's a substring of it:
UX128_CR0,3,128,176
This has three important parts:
The first 128 resizes the image by width, keeping ratio
The second 128 controls the container width that the image appears in
176 controls the container height that the image appears in.
So, we can view the structure like this:
UX<image_width>_CR0,3,<container_width>,<container_height>
As an example, to double the image size:
UX256_CR0,3,256,352_AL_.jpg
(Click here to see: https://m.media-amazon.com/images/M/MV5BZWMyYzFjYTYtNTRjYi00OGExLWE2YzgtOGRmYjAxZTU3NzBiXkEyXkFqcGdeQXVyMzQ0MzA0NTM#.V1_UX256_CR0,3,256,352_AL.jpg
Update: Example of how you might do it in Python.
import re
resize_factor = 2 # Image size multiple
url = "https://m.media-amazon.com/images/M/MV5BZWMyYzFjYTYtNTRjYi00OGExLWE2YzgtOGRmYjAxZTU3NzBiXkEyXkFqcGdeQXVyMzQ0MzA0NTM#._V1_UX128_CR0,3,128,176_AL_.jpg"
#
# resize_factor : Image size multiplier (e.g., resize_factor = 2 doubles the image size, positive integer only)
# url : full URL of the image
# return : string of the new URL
#
def getURL(resize_factor, url):
# Regex for pattern matching relevant parts of the URL
p = re.compile(".*UX([0-9]*)_CR0,([0-9]*),([0-9]*),([0-9]*).*")
match = p.search(url)
if match:
# Get the image dimensions from the URL
img_width = str(int(match.group(1)) * resize_factor)
container_width = str(int(match.group(3)) * resize_factor)
container_height = str(int (match.group(4)) * resize_factor)
# Change the image dimensions
result = re.sub(r"(.*UX)([0-9]*)(.*)", r"\g<1>"+ img_width +"\g<3>", url)
result = re.sub(r"(.*UX[0-9]*_CR0,[0-9]*,)([0-9]*)(.*)", r"\g<1>"+ img_width +"\g<3>", result)
result = re.sub(r"(.*UX[0-9]*_CR0,[0-9]*,[0-9]*,)([0-9]*)(.*)", r"\g<1>"+ container_height +"\g<3>", result)
return result
#
# Test
#
print (getURL(resize_factor,url))
Edit: Typo

Shape error while converting Image to JSON file

I am trying to convert image to JSON file and POST it with REST API by using MLFLow. Below you can see my code. I got an error like "cannot reshape array of size 535500 into shape (1,4096)". Can you please help me. Thank you in advance.
import json
import cv2
import requests
import base64
import numpy as np
from PIL import Image
data = np.asarray(Image.open('Dataset/test2/dog_PNG50348.png').convert('LA'))
data = data.reshape((1, 64*64))
columns = [f"col_{c}" for c in range(0, data[0].shape[0])]
dct = {"columns": columns, "data": [data[0].tolist()]}
print(json.dumps(dct, indent=2) + "\n")
#print(data)
headers = {'Content-Type': 'application/json'}
request_uri = 'http://127.0.0.1:5000/invocations'
if __name__ == '__main__':
try:
response = requests.post(request_uri, data=json.dumps(dct,indent=2)+"\n", headers=headers)
print(response.content)
print('done!!!')
except Exception as ex:
raise (ex)

marking box in an image from response request python

import requests
import cv2
frame=cv2.imread('C:\\Users\\aaa\\Downloads\\abc.jpg')
url = 'https://app.nanonets.com/api/v2/ObjectDetection/Model/4729a79f-ab19-4c1b-8fe9'
data = {'file': open('C:\\Users\\aaa\\Downloads\\abc.jpg', 'rb')}
response = requests.post(url, auth=requests.auth.HTTPBasicAuth('S5zsN-yFZJxRH9tMwsaHUCxJg3dZaDWj', ''), files=data)
print (type(response))
print(response)
I uploaded an image for object detection. I got the response like this.
{"message":"Success","result":[{"message":"Success","input":"abc.jpg","prediction":[{"label":"car","xmin":411,"ymin":332,"xmax":585,"ymax":462,"score":0.99097943},{"label":"car","xmin":496,"ymin":170,"xmax":592,"ymax":248,"score":0.96399206},{"label":"car","xmin":223,"ymin":147,"xmax":294,"ymax":202,"score":0.9383388},{"label":"car","xmin":164,"ymin":130,"xmax":230,"ymax":175,"score":0.8968652},{"label":"car","xmin":448,"ymin":489,"xmax":623,"ymax":540,"score":0.8311123}],"page":0,"request_file_id":"5a8549f1-fb2c-487a-83b5-234608b3168b","filepath":"uploadedfiles/4729a79f-ab19-fac0fb807e6d/PredictionImages/53207.jpeg"}]}
I want to make a box in the image with the given coordinates.
import requests
import cv2
import math
from PIL import Image, ImageDraw
import json
frame=cv2.imread('C:\Users\aaa\Downloads\abc.jpg')
url = 'https://app.nanonets.com/api/v2/ObjectDetection/Model/4729a79f-ab19-4c1b-8fe9'
data = {'file': open('C:\Users\aaa\Downloads\abc.jpg', 'rb')}
response = requests.post(url, auth=requests.auth.HTTPBasicAuth('S5zsN-yFZJxRH9tMwsaHUCxJg3dZaDWj', ''), files=data)
predictions = json.loads(response.text)['result'][0]['prediction']
img = Image.open('C:\Users\aaa\Downloads\abc.jpg')
img1 = ImageDraw.Draw(img)
for prediction in predictions:
shape = [(prediction['xmin'], prediction['ymin']), (prediction['xmax'], prediction['ymax'])]
img1.rectangle(shape, fill ="# ffff33", outline ="red")
img.show()

How to send an image from a telegram bot

I have my bot working by now, but the thing is it can only send text. I have seen in the Bot API there are functions to send photos, videos... but I can't get it to work. Someone has achieved it? I'm using python source code from yukuku/telebot
elif text == '/image':
img = Image.new('RGB', (512, 512))
base = random.randint(0, 16777216)
pixels = [base+i*j for i in range(512) for j in range(512)] # generate sample image
img.putdata(pixels)
output = StringIO.StringIO()
img.save(output, 'JPEG')
reply(img=output.getvalue())
When I change the code, nothing happened.
img = Image.open('image.png')
img.show()
Please help me. I need the correct code. Sorry for my bad English.
I have included two functions, one is good for sending local images, the other one is good for sending remote images.
def sendImage():
url = "https://api.telegram.org/bot<Token>/sendPhoto";
files = {'photo': open('/path/to/img.jpg', 'rb')}
data = {'chat_id' : "YOUR_CHAT_ID"}
r= requests.post(url, files=files, data=data)
print(r.status_code, r.reason, r.content)
def sendImageRemoteFile(img_url):
url = "https://api.telegram.org/bot<Token>/sendPhoto";
remote_image = requests.get(img_url)
photo = io.BytesIO(remote_image.content)
photo.name = 'img.png'
files = {'photo': photo}
data = {'chat_id' : "YOUR_CHAT_ID"}
r= requests.post(url, files=files, data=data)
print(r.status_code, r.reason, r.content)
The solution is
elif 'Hi' in text:
reply(img=urllib2.urlopen('img url').read())
or
if text == 'help':
reply(img=urllib2.urlopen('img url').read())
Before sending the photo, you have to do output.seek(0) to put the cursor back to the beginning of the file, else it will be read as zero
I understand the question. Here's the answer:
def sendImageFromUrl(url):
#this tweak added if request image failed
headers = {'user-agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'}
response = requests.get(url, headers=headers)
#response = requests.get(url)
output = StringIO(response.content)
img = Image.open(output)
img.save(output, 'JPEG')
resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
('chat_id', str(chat_id)),
('caption', 'Your Caption'),
], [
('photo', 'image.jpg', output.getvalue()),
])
Make sure your server does have python module: requests.
You can download here: https://pypi.python.org/pypi/requests#downloads
And put in your application like this
/myapp/app.yaml
/myapp/main.py
/myapp/requests/packages/
/myapp/requests/__init__.py
/myapp/requests/adapters.py
etc...
Credit: https://stackoverflow.com/a/17128168/1097372
Put in main.py after line 10
import requests
from StringIO import StringIO

Categories

Resources