I am converting canvas to url and sending it to python via ajax POST request using Flask. I am getting the url all right, even printed it and both are same. But I don't get how to get the image back. I search internet, most answers say to use decode method but I get error that decode cannot work on 'str' object. I also tried using StringIO with Image.open which also gives error. So, can anyone please tell me how to do that?
My JS:
$SCRIPT_ROOT = {
{
request.script_root | tojson | safe
}
};
$(function() {
$("#pic").bind('click', function() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
var imgURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: $SCRIPT_ROOT + '/send_pic',
data: {
imageBase64: imgURL
}
}).done(function() {
console.log("sent");
});
});
My python code:
#app.route('/send_pic',methods=['GET','POST'])
def button_pressed():
print("Image recieved")
data_url = request.values['imageBase64']
img = Image.open(StringIO(data_url))
img = np.array(img)
cv2.imshow(img)
cv2.waitKeys(0)
cv2.destroyAllWindows()
return ""
the value of data_url is :
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAgAElEQVR4XpS9+betWVUluE5/bvPufW28ICIIuoig7wVM1LJJshlVllU1atSoLu1RkUYxUEQQMzX9R/KXzBpllppWplqpFI0BCIiYoBAESBNE8+LF625/7mlrrDnX3Ht93z1BZl0N3r2n+b797b32XHO1u/OLP/czq9VqaYvl3Farha1WK/O/l52l9Tpd63c6fK+zsN5waIPR2AbjTbNOz4bLhXVXKzP/18w63aGtVn1bdHrmr3Q7fTNbWafr/7u0TsdsuZyb/3RWC+v4C/5+xz/bsxXeMbOl2Wrpn+9Yp9u1Tq+DMc3nC7zZ7cZ1V/57x3r+ndUS9+DFO7Zc+t9+9a51/DPdrvlQben365it/Jrxu3/F/O8FvtPt9myx8EH4M/mT+fwsrYsB4iJ4Jt65m/7lePkpH9vKr4rvLlen1u91rdPhd1Yrf3a/q/+LX2M+NAmGZ/afgfUwVv+Mf221XNmqy+/5ZzAWnyt/bl+OFUfJD0yt53fp+hz7+1xf//G5w+3x+folnzu/1qrr34xxxbyVvzFfmm6Oxa9df5YccxnHyjrlz4V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MXqbDmvFbBeuHqCHAKawdrFCaflDXG1khtzBSxpps0QSGlGUUhunLMqgvG54trWfyP6XetER5Z3UUxmIQCEXHM652vp4XTrkfkULKgYELQrc573/12tJdBpwFnNeFDGvaGTENwH7d3JegO6AB2/1UAmm+wLPhanipwxfERBntVSbUVsRavmTktv4zcGTLKkc4f/aD0UCRdaluc+w1F3VXQYkQgo3xGoVtNa0l07ZiNN7fQpNA3LNMcBthEjk+e1b6cL2w2nVFC/ELo3Oxm5sKOj4/hMGcCYseuP/MszMzzO0NEB709j0da2d9KGinaiBQzh054l+9Bn+10ikkt52uL4eaNqGcCUIQU5E1c3kctLHve5zrJsjGT+YmNGBsOCYYtB7aGfkZDEq1C4JttiEspUkuzCiAbKWUBhHym1mYE01T+U6s/egKcMgchctWVkRJFY14xn0m6a/1eLSYu45PpG8Mqo4teUppjWgHq0hmAjl7rkcqTx8pFwL5Bq/IyhxW4IT/yI5VNrgBAi3qGqZj3a5NJqUyGT43EX0Un49oyb/PrZNA5yhlY9V3qQZF8i4L8yEZLrKoAYFGSBGyxxc7D7/4p5NJ50qObKjABzTuL0s8CU8Vb7HtrmWMhgY4AACAASURBVMEATmltghqGTgKUBUeO0lL3VJEX13WTqDjZWUkumzjFo5r+CjTTqwW70uIyHehIjgxlCVxMiIMIGwNyUfx/q7lUW51sb5+z3YsXkeLgeVtOl90UnEwcpFY2OT0FaCo7HnR46dUCc
Thanks!!!
From your code I understand that in your endpoint you expect base64 data. If so you can try something like this:
import base64
from io import BytesIO
#app.route('/send_pic',methods=['GET','POST'])
def button_pressed():
print("Image recieved")
data_url = request.values['imageBase64']
# Decoding base64 string to bytes object
img_bytes = base64.b64decode(data_url)
img = Image.open(BytesIO(img_bytes))
img = np.array(img)
cv2.imshow(img)
cv2.waitKeys(0)
cv2.destroyAllWindows()
return ""
Edit:
If data you sending is not base64 then you can try to transform it using numpy like this:
from flask import request
...
img_data = np.fromstring(request.data, np.uint8)
# Do what you want with it
cv2.imshow(img)
Edit 2:
Based on value you provided you must split value from request to get base64 image data:
#app.route('/send_pic',methods=['GET','POST'])
def button_pressed():
print("Image recieved")
data_url = request.values['imageBase64']
# Decoding base64 string to bytes object
offset = data_url.index(',')+1
img_bytes = base64.b64decode(data_url[offset:])
img = Image.open(BytesIO(img_bytes))
img = np.array(img)
cv2.imshow(img)
cv2.waitKeys(0)
cv2.destroyAllWindows()
return ""
Related
I'm facing an issues sending an Image (np.ndarray) over my python server to my javascript client.
Starting with the python server, I process the img like this:
1) Load img as np.ndarray
2) enc_img = base64.b64encode(img.copy(order='C'))
3) utf8_img = enc_img.decode("utf-8")
4) json = {
...
"img": utf8_img,
...
}
5) req_return = json.dumps(json, ensure_ascii=False)
// The fct below I found on SO ..
For the client (javascript) I do the following:
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode(parseInt(p1, 16))
}))
}
img_64 = b64EncodeUnicode(jsonRes.fs_dict.face)
var src = "data:image/jpg;base64,";
src += img_64;
var newImage = document.createElement('img');
newImage.src = src;
newImage.width = newImage.height = "100";
document.querySelector('#face_img').innerHTML = newImage.outerHTML;
To sum it up, I want to send an image over the API and convert it into a valid base64 format to display via html. After experimenting a little I sometimes got "no valid base64 format" but with the provided code I'm not getting any error. The image doesn't show up though.
It is important to not save the file in my scenario.
So I figured the problem. I had troubles encoding the image (nparray) to a proper base64 encoding.
pil_img = Image.fromarray(nparray_img)
buff = BytesIO()
pil_img.save(buff, format="JPEG")
enc_img = base64.b64encode(buff.getvalue()).decode("utf-8")
this resolved the encoding issues for me.
I then return a dictionary containing the img like so:
res = {
"img": enc_img
}
return res
After converting it to JSON via
json.dumps(res), I send it via the API to my JavaScript Client.
When receiving the JSON, I first parse it to access the dictionary again like so:
jsonRes = JSON.parse(xhr.responseText);
img = jsonRes.img;
and finally output it via HTML by using jQuery:
var source = "data:image/jpg;base64,";
source += img;
$(document).ready(function() {
$('#face_img').attr('src',source).height(100).width(100).show();
});
The
('#face_img')
is an ID of my HTML, looking like the following:
<img id="face_img" src="" alt="img_face" />
Hope this helps someone.
I built a simple project using javascript and FastAPI. I would like to POST canvas image data in javascript to the server(FastAPI).
But, I get the 422 Unprocessable Entity error
# FastAPI
#app.post("/post")
async def upload_files(input_data: UploadFile = File(...)):
return JSONResponse(status_code = 200, content={'result' : 'success'})
// javascript
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
imageData = ctx.getImageData(0, 0, 112, 112);
fetch("http://{IP}/post", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
input_data: imageData,
}),
})
.then((response) => response.json())
here is my code. I am new one in javascript. so I don't know how can post data to server.
How can I do? Thanks in advance.
MatsLindh's way is correct but you can try upload image by formdata so you haven't convert to base64 then convert back to image
const dataURItoBlob = function(dataURI : string) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString : string;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
const url = canvas.toDataURL()
const file = dataURItoBlob(url)
//add file to formdata
const form = new FormData()
form.append('file', item.file)
//post this form in body
UploadFile expects a file being posted to the endpoint in the multipart/form-data format - i.e. as a regular POST with a bit of added metadata.
Since you're retrieving the image data and submitting it as JSON body, that won't match the expected format. You also want to use canvas.toDataURL() to convert the content to base64 before trying to submit it through your API to avoid any UTF-8 issues with JSON.
const pngData = canvas.toDataURL();
// then in your request:
body: JSON.stringify({
input_data: pngData,
}),
To handle this request change your view function signature to receive an input_data parameter (and use a better endpoint name than post):
#app.post("/images")
async def upload_files(input_data: str = Body(...)):
# check the expected format (content-type;<base64 content>)
# .. and decode it with base64.b64decode()
return {'content': input_data}
I'm using code from this and that answer to send a base64 encoded image to a python FastAPI backend.
The client side looks like this:
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
function makeBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], { type: contentType });
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
...
toDataURL(
images[0], // images is an array of paths to images
function(dataUrl) {
console.log('RESULT:', dataUrl);
$.ajax({
url: "http://0.0.0.0:8000/check/",
type: 'POST',
processData: false,
contentType: 'application/octet-stream',
data: makeBlob(dataUrl)
}).done(function(data) {console.log("success");}).fail(function() {console.log("error");});
}
);
And the server side is as follows:
#app.post("/check")
async def check(file: bytes = File(...)) -> Any:
// do something here
I'm only showing the signature of the endpoint because for now nothing much is happening in it anyway.
Here is the output of the backend when I call it as shown above:
172.17.0.1:36464 - "OPTIONS /check/ HTTP/1.1" 200
172.17.0.1:36464 - "POST /check/ HTTP/1.1" 307
172.17.0.1:36464 - "OPTIONS /check HTTP/1.1" 200
172.17.0.1:36464 - "POST /check HTTP/1.1" 422
So, in short, I keep getting 422 error codes, which means that there is a mismatch between what I send and what the endpoint expects, but even after some reading I'm still not clear on what exactly is the issue. Any help would be most welcome!
As described in this answer, uploaded files are sent as form data. As per FastAPI documentation:
Data from forms is normally encoded using the "media type"
application/x-www-form-urlencoded when it doesn't include files.
But when the form includes files, it is encoded as
multipart/form-data. If you use File, FastAPI will know it has to get
the files from the correct part of the body.
Regardless of what type you used, either bytes or UploadFile, since...
If you declare the type of your path operation function parameter as
bytes, FastAPI will read the file for you and you will receive the
contents as bytes.
Hence, the 422 Unprocessable entity error. In your example, you send binary data (using application/octet-stream for content-type), however, your API's endpoint expects form data (i.e., multipart/form-data).
Option 1
Instead of sending a base64 encoded image, upload the file as is, either using an HTML form, as shown here, or Javascript, as shown below. As others pointed out, it is imperative that you set the contentType option to false, when using JQuery. Using Fetch API, as shown below, it is best to leave it out as well, and force the browser to set it (along with the mandatory multipart boundary). For async read/write in the FastAPI backend, please have a look at this answer.
app.py:
import uvicorn
from fastapi import File, UploadFile, Request, FastAPI
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
#app.post("/upload")
def upload(file: UploadFile = File(...)):
try:
contents = file.file.read()
with open("uploaded_" + file.filename, "wb") as f:
f.write(contents)
except Exception:
return {"message": "There was an error uploading the file"}
finally:
file.file.close()
return {"message": f"Successfuly uploaded {file.filename}"}
#app.get("/")
def main(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
templates/index.html
<script>
function uploadFile(){
var file = document.getElementById('fileInput').files[0];
if(file){
var formData = new FormData();
formData.append('file', file);
fetch('/upload', {
method: 'POST',
body: formData,
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
}
}
</script>
<input type="file" id="fileInput" name="file"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
If you would like to use Axioslibrary for the upload, please have a look at this answer.
Option 2
If you still need to upload a base64 encoded image, you can send the data as form data, using application/x-www-form-urlencoded as the content-type; while in your API's endpoint, you can define a Form field to receive the data. Below is a complete working example, where a base64 encoded image is sent, received by the server, decoded and saved to the disk. For base64 encoding, the readAsDataURL method is used on client side. Please note, the file writing to the disk is done using synchronous writing. In scenarios where multiple (or large) files need to be saved, it would be best to use async writing, as described here.
app.py
from fastapi import Form, Request, FastAPI
from fastapi.templating import Jinja2Templates
import base64
app = FastAPI()
templates = Jinja2Templates(directory="templates")
#app.post("/upload")
def upload(filename: str = Form(...), filedata: str = Form(...)):
image_as_bytes = str.encode(filedata) # convert string to bytes
img_recovered = base64.b64decode(image_as_bytes) # decode base64string
with open("uploaded_" + filename, "wb") as f:
f.write(img_recovered)
return {"message": f"Successfuly uploaded {filename}"}
#app.get("/")
def main(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
templates/index.html
<script type="text/javascript">
function previewFile() {
const preview = document.querySelector('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result; //show image in <img tag>
base64String = reader.result.replace("data:", "").replace(/^.+,/, "");
uploadFile(file.name, base64String)
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile(filename, filedata){
var formData = new FormData();
formData.append("filename", filename);
formData.append("filedata", filedata);
fetch('/upload', {
method: 'POST',
body: formData,
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
}
</script>
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
actually there are many answers for this question. But my problem is,
i want to generate pdf dynamically with 5 external(URL) images. Im using PDFmake node module.
it supports only two ways local and base64 format. But i don't want to store images locally.
so my requirement is one function which takes url as parameter and returns base64.
so that i can store in global variable and create pdfs
thanks in advance
function urlToBase(URL){
return base64;
}
var img = urlToBase('https://unsplash.com/photos/MVx3Y17umaE');
var dd = {
content: [
{
text: 'fjfajhal'
},
{
image: img,
}
]
};
var writeStream = fs.createWriteStream('myPdf.pdf');
var pdfDoc = printer.createPdfKitDocument(dd);
pdfDoc.pipe(writeStream);
pdfDoc.end();
im using PDFmake module from npm
The contents of the remote image can first be fetched with an HTTP request, for example using the ubiquitous request npm module. The image string contents can then be transformed to a buffer and finally converted to a base64 string. To complete the transformation, add the proper data-url prefix, for example, data:image/png,base64, to the beginning of the base64 string.
Here is a rough example for a PNG image:
const request = require('request-promise-native');
let jpgDataUrlPrefix = 'data:image/png;base64,';
let imageUrl = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
request({
url: imageUrl,
method: 'GET',
encoding: null // This is actually important, or the image string will be encoded to the default encoding
})
.then(result => {
let imageBuffer = Buffer.from(result);
let imageBase64 = imageBuffer.toString('base64');
let imageDataUrl = jpgDataUrlPrefix+imageBase64;
console.log(imageDataUrl);
});
I cannot upload a canvas.toDataURL image: I get the warning:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/
and then the error:
no element found testSave.php:23:1
As in this tutorial, my JavaScript is:
var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData );
and testSave.php:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
I found an ugly solution to my problem:
In HTML <head>, add:
<script src="../static/js/jquery-1.11.2.js"></script>
Replace the JavaScript part of the question with:
var dataURL = canvas.toDataURL('image/png');
$.ajax({
type: "POST",
url: "upload_ajax",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
// If you want the file to be visible in the browser
// - please modify the callback in javascript. All you
// need is to return the url to the file, you just saved
// and than put the image in your browser.
});
Use Flask instead of PHP, with the relevant part of the code being:
from flask import json as jsonflask
import cv2
import uuid
import os
import base64
import numpy as np
import StringIO
import urllib
from PIL import Image
def request_to_nparray(request):
output=request.form['imgBase64']
head = "data:image/png;base64,"
assert(output.startswith(head))
imgdata = base64.b64decode(output[len(head):])
imgF = StringIO.StringIO()
imgF.write(imgdata)
imgF.seek(0)
img = Image.open(imgF)
buf = np.fliplr(np.asarray(img))
buf = np.asarray(img)
bufshape=buf.shape
rgbFrame = np.zeros(bufshape, dtype=np.uint8)
rgbFrame[:, :, 0] = buf[:, :, 2]
rgbFrame[:, :, 1] = buf[:, :, 1]
rgbFrame[:, :, 2] = buf[:, :, 0]
ourframe = np.copy(rgbFrame)
return ourframe
`#app.route('/upload_ajax', methods = ['POST'])
def ajax_request():
photo_array= request_to_nparray(request)
f_name = str(uuid.uuid4()) + '.jpg'
_photo_path= os.path.join(app.config['UPLOAD_FOLDER'], f_name)
cv2.imwrite(_photo_path, photo_array)
return jsonflask.dumps({'filename':f_name})`