Sending Image from React-Native app to Django Models - react-native

I am building a react-native app with a Django backend. I am trying to send a user input image to Django to be saved as an ImageField in Django Models without using REST-FRAMEWORK. How can I do that?

Suppose you have a model called Image then you can save the image using the following way.
from django.http import HttpResponse
from django.core.exceptions import PermissionDenied
def saveImage(request):
if request.POST:
if 'image' not in request.POST:
return HttpResponse('Bad POST Parameters. Please use "image" key')
image = request.POST['image']
Image.objects.create(image=image)
return HttpResponse('Image successfully saved')
else:
raise PermissionDenied

Related

how can I render an url on google colab?

I have this in a cell:
import requests
import json
response = requests.get("https://api.nasa.gov/planetary/apod?
api_key=YF6oJUH1StX0gV4o51ATSsn3qr9S7zzCLjZypQYu")
json_data=response.json()
address=json_data["hdurl"]
print(address)
and the outcome is: https://apod.nasa.gov/apod/image/2004/LightPollutionPan_Slovinsky_2048.jpg
The problem is how to "open" the url?
I have tried %%HTML and gave me a gray screen, I tried also webbrowser but I got False as the outcome, this seems to be easy but I can't figure out, any help would be appreciated.
You can render the remote image using IPython module.
import IPython
IPython.display.Image(url='https://google.com/favicon.ico')
So the code that you wantis something like this:
import requests
import json
from IPython.display import Image as RenderImage
response = requests.get("https://api.nasa.gov/planetary/apod?api_key=YF6oJUH1StX0gV4o51ATSsn3qr9S7zzCLjZypQYu")
json_data=response.json()
address=json_data["hdurl"]
RenderImage(url='https://apod.nasa.gov/apod/image/2004/LightPollutionPan_Slovinsky_960_labeled.jpg')

How do I solve this CORS error when using TensorFlow.js to classify Cloudinary images?

I am using the Vuetify Cloudinary Upload component to upload pictures to my Vue application. I then want to run the TensorFlow.js library on them to classify objects. Unfortunately, I get this error:
DOMException: Failed to execute 'texImage2D' on
'WebGL2RenderingContext': The image element contains cross-origin
data, and may not be loaded.
Here is my relevant code:
import * as cocoSSD from '#tensorflow-models/coco-ssd';
let images = document.getElementsByTagName("img");
let imagePromises = [];
for (let image of images)
{
image.setAttribute('crossOrigin', 'anonymous');
imagePromises.push(this.model.detect(image)
.then(classified => this.objects.push(classified))
.catch(e => {console.log(e)})
)}
await Promise.all(imagePromises);
The image has to be served by a server which enables cross origin. Using the image directly from the file system will always throw the cors error issue.
Then the crossOrigin attribute of the image has to be set either directly on the html
<img src="url" crossorigin="anonymous">
or in the js script
image.setAttribute('crossOrigin', 'anonymous');
// or
image.crossOrigin = "anonymous";

Problem in creating asset of local static image using react-native-photos-framework

I am using react-native-photos-framework for creating user defined album and creating assets into device native gallery.
In my app I gives an user defined album creation functionality to user. For that I am displaying a simple modal with input field where user can type album name and 'OK' and 'CANCLE' button.
What I want ?
I want that when user click on 'OK' button after typing album name in input field, a typed album should be created in gallery and one by default image (which is in my local directory) should added to that album.
Here is the code that i used :
createAlbum() {
RNPhotosFramework.createAlbum(this.state.createAlbumName).then((album) => {
RCTCameraRollRNPhotosFrameworkManager.createAssets({
images : [{ uri : '../assets/logo.png' }],
album : album,
includeMetadata : true
});
}).catch((error)=>{
alert("Error in creating album : \n"+JSON.stringify(error));
});
}
As you can see, I am first creating album which is creating successfully in gallery, But assets is not copying in that album. It is giving me this error :
Could not find image file:///Users/vision/Library/Developer/CoreSimulator/Devices/E5AA1780-A55C-4C67-95A5-222E4AS3PA23/data/Containers/Bundle/Application/5E37FAF5-15DD-483B-3BD6-C311C587SD8/CameraApp.app/../assets/imgs/logo.png
I have also used require() to get image uri as follow :
images : [{ uri : require('../assets/logo.png' )}],
but then app will crash.
Here is the my project structure :
Please help me how I can create asset of local static image using react-native-photos-framework. I am new to react native !!!
If anyone also running in this problem I have solved problem using this answer.
To solve the problem first install react-native-fs.
Then import it in your project.
const RNFS = require('react-native-fs');
Then I used RNFS.MainBundlePath to get my app root path and add assets before my actual path.
Here is code :
createAlbum() {
RNPhotosFramework.createAlbum(this.state.createAlbumName).then((album) => {
RCTCameraRollRNPhotosFrameworkManager.createAssets({
images : [{uri:RNFS.MainBundlePath+'assets/src/assets/imgs/logo.png'}],
album : album,
includeMetadata : true
}).then((result)=>{
alert(JSON.stringify(result));
}).catch((error)=>{
alert("Error in creating assets.\n"+JSON.stringify(error));
});
});
}
Hope it will help someone.

Display PDF Content in an Aurelia View

I have some PDF files that I need to display in an Aurelia View.
The files are not available by direct link
I have an API function that returns a byte array.
In ASP.Net, I have some control over the response object's headers and content type, and can BinaryWrite the contents into the response.
I can't figure out how to do this in Aurelia.
Any suggestions?
Edit:
I'm attempting to use pdf.js as suggested. Injection in Aurelia fails.
import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-fetch-client";
import {PDF} from "pdfjs-dist"
#inject(Router, HttpClient, PDF)
export class PDFView {
constructor(router, http, pdf) {
this.router = router;
this.http = http;
this.pdf = pdf;
}
The console displays this error:
Inner Error:
Message: key/value cannot be null or undefined. Are you trying to inject/register something that doesn't exist with DI?
Inner Error Stack:
Error: key/value cannot be null or undefined. Are you trying to inject/register something that doesn't exist with DI?
at Container.get (http://localhost:65397/jspm_packages/npm/aurelia-dependency-injection#1.0.0-beta.1.2.3/aurelia-dependency-injection.js:480:15)
at Object.invoke (http://localhost:65397/jspm_packages/npm/aurelia-dependency-injection#1.0.0-beta.1.2.3/aurelia-dependency-injection.js:341:81)
at InvocationHandler.invoke (http://localhost:65397/jspm_packages/npm/aurelia-dependency-injection#1.0.0-beta.1.2.3/aurelia-dependency-injection.js:300:168)
at Container.invoke (http://localhost:65397/jspm_packages/npm/aurelia-dependency-injection#1.0.0-beta.1.2.3/aurelia-dependency-injection.js:564:25)
at StrategyResolver.get (http://localhost:65397/jspm_packages/npm/aurelia-dependency-injection#1.0.0-beta.1.2.3/aurelia-dependency-injection.js:127:37)
at Container.get (http://localhost:65397/jspm_packages/npm/aurelia-dependency-injection#1.0.0-beta.1.2.3/aurelia-dependency-injection.js:501:23)
at eval (http://localhost:65397/jspm_packages/npm/aurelia-templating#1.0.0-beta.1.2.7/aurelia-templating.js:3925:73)
End Inner Error Stack
------------------------------------------------
The import statement must be failing, yet pdfjs appears to load successfully as I receive status 200 for both pdfjs-dist#1.5.294.js and pdfjs when the page loads.
I can find no samples of Aurelia / pdfjs apps.
Repeating: I need to embed the stream as the PDF is not available via HTTP.
I'm not sure where to go from here
As far as I know there is nothing Aurelia-specific about loading pdf files.
You can use pdf.js. It has method getDocument that accepts binary data stored in byte array.
Then you can place a canvas inside your view, load pdf data during view activation and render pages into it using pdf.js after html is attached. For example code check answer by toddmo for this post: Pdf.js and viewer.js. Pass a stream or blob to the viewer

get an jpg image from a mobilefirst http adapter

im working in a mobilefirst adapter (6.3) that need to pass an image from an url that is in the internarl network file system(example :http://www.up.edu.pe/RED_Compartir/facebook.png) but i cant get the data correctly, the img data isnt in the text variable:
Here is my server side code:
function getImage(id){
var input = {
method : 'get',
returnedContentType : 'plain',
path : '/someUrl/someUrl2/'+id+'.jpg'
};
return {
out: Base64.encode(WL.Server.invokeHttp(input).text)
};
}
Here is my client code to process de image:
function getImageFrom() {
execMobileFirstAdapter("adapterName", "method", ["parameter"]).then(function (data){
WL.Logger.debug("OK")
var imageBase = data.invocationResult.out;
document.getElementById('imageServer').setAttribute( 'src', 'data:image/jpeg;base64,'+ imageBase );
}).fail(function(data){
WL.Logger.debug("error");
})
}
Is there a way to return the base64 from a jpg image from a mobilefirst adapter?
Ive used this example:
https://www.ibm.com/developerworks/community/blogs/mobileblog/entry/ibm_worklight_adapter_accessing_an_image?lang=en
and Works perfectly but i need to do this only with JavaScript in the server. is this posible?
Is there a way to return the base64 from a jpg image from a
mobilefirst adapter?
I've used this example:
https://www.ibm.com/developerworks/community/blogs/mobileblog/entry/ibm_worklight_adapter_accessing_an_image?lang=en
and Works perfectly but i need to do this only with JavaScript in the
server. is this possible?
The easiest approach is in fact to implement it the way the example does it in the article you've provided.
The only other way is to find a JavaScript lib that does base64 encoding and try to add this lib to the adapter and then use it.
Note that JavaScript adapters do not support adding additional files to the adapter, so that means you need to take the entire implementation of whichever lib you'll find and put it inside your adapter code. Not so nice. Also does not guarantee it'll work.
Additionally, are you calling your adapter from inside a Cordova plug-in? That was strange. Why? Why not just use the WL.Client.invokeProcedure API... just like in the article...