startActivityForResultIntent result=None - qpython

I'm using qpython on Android and am attempting the following:
import androidhelper
droid = androidhelper.Android()
action = "android.intent.action.OPEN_DOCUMENT"
mimetype = "image/*"
categories = ["android.intent.category.OPENABLE"]
intent = droid.makeIntent(action, None, mimetype, None, categories).result
activity = droid.startActivityForResultIntent(intent)
After selecting an image in the picker, the result is:
Result[id=1, result=None, error=None]
Why can't I get a url result from this?
Thanks in advance!

Related

How to convert HEIC to JPG in React?

HEIC is Apple's own format to store high resolution images made with iOS cameras. But I would store on backend JPG, because HEIC is not displayed in most browsers, not even in Safari.
SOLUTION 1
I tried this for the conversion:
const buffer = Buffer.from(await file.arrayBuffer())
const d = heicConvert({ buffer, format: 'JPEG' })
const imgBase64 = btoa(
d.reduce((data, byte) => `${data}${String.fromCharCode(byte)}`, '')
)
but because I use Next.js it is not compatible with it.
Failed to compile.
./node_modules/libheif-js/libheif/libheif.js
Module not found: Can't resolve 'fs' in '/Users/janoskukoda/Workspace/tikex/portal/team/node_modules/libheif-js/libheif'
SOLUTION 2
I tried this also:
export default uploadImage
const buffer = await file.arrayBuffer()
const image = sharp(buffer)
const metadata = await image.metadata()
if (metadata.format === 'heic') {
// Convert the image to JPG
const jpgBuffer = await image.jpeg().toBuffer()
// Encode the JPG image as a base64 string
const imgBase64 = btoa(
jpgBuffer.reduce((data, byte) => `${data}${String.fromCharCode(byte)}`, '')
)
}
But I can not compile, seems sharp is not recommended to use in client side.
Do you have any other way to do it?
Anyway idea comes here: https://itnext.io/tackling-iphone-or-ipad-images-support-in-browser-8e3e64e9aaa1
If you show me a solution uses serverless api, it is also ok. It is important file comes from html input element.
SOLUTION 3
import loadImage from 'blueimp-load-image'
convertedImage = await new Promise((resolve, reject) => {
loadImage(
propsAndFile.file,
resolve,
{ orientation: true, canvas: true },
reject
)
})
Before getting to the answer: You can never trust data uploaded by a client — you must always validate/convert using a process that is not accessible by a user (a backend process) to ensure data validity: even if there are mechanisms in place to validate received network requests as coming from an authenticated user on your site, any user can still use developer tools to execute arbitrary JavaScript and send whatever kinds of network requests with whatever payloads that they want to.
Regarding iOS devices and getting JPEG instead of HEIF from a file input: You don't need to do this yourself — iOS can do it for you.
<input type="file"> elements support an accept attribute that can be used to restrict the kinds of file media types that can be uploaded: read more at the Limiting accepted file types section of the MDN documentation article for <input type="file">.
Below is an example which shows how to use that attribute. When an iOS user selects the input, they can choose to take a photo using their camera or select one from the photo library. iOS will perform the necessary file conversion to JPEG automatically in both of these cases (for example, even when a selected image from the photo library is in HEIF format). The example demonstrates this when you try it with an HEIF-encoded image on an iOS device:
const input = document.getElementById('image-upload');
const output = document.getElementById('output');
const updateDisplayedFileInfo = () => {
const file = input.files?.[0];
if (!file) {
output.textContent = 'No file selected';
return;
}
const dateModified = new Date(file.lastModified).toISOString();
const {name, size, type} = file;
const data = {
dateModified,
name,
size,
type,
};
const json = JSON.stringify(data, null, 2);
output.textContent = json;
};
input.addEventListener('change', updateDisplayedFileInfo);
updateDisplayedFileInfo();
pre { background-color: hsla(0, 0%, 50%, 0.1); padding: 0.5rem; } code { font-family: monospace; }
<input id="image-upload" type="file" accept="image/jpeg" />
<pre><code id="output"></code></pre>
Install the heic2jpeg library by running the following command in your terminal:
npm install heic2jpeg
Import the heic2jpeg library in your React component:
import heic2jpeg from 'heic2jpeg';
Convert the HEIC file to JPG by calling the convert method of the heic2jpeg library and passing in the HEIC file as an argument:
const jpegData = await heic2jpeg.convert(heicFile);
You can then use the jpegData to create a new JPG file or display it in an img element:
const jpegFile = new File([jpegData], 'image.jpg', { type: 'image/jpeg' });
// or
const imageElement = document.createElement('img');
imageElement.src = URL.createObjectURL(jpegFile);
document.body.appendChild(imageElement);
Note that the heic2jpeg library requires the canvas and process modules to be available in the global context, so you may need to include these modules in your application as well.

How to upload image to image column from SharePoint List using REST API(React)

I have a problem of uploading image to image column in sharepoint online via pnpjs
I don't know how to convert image and upload to image column in sharepoint list.
I tried lot of ways (by convert image to blob, filedata) nothing works.
Keep in much this is not an attachments for the list..
It's a new column(image) in sharepoint list
reference image click here
Looks like the image is not stored in the list. JSON is stored. So you can just upload image to site assets (that's what sharepoint does when you set the image manually) and then put the json to the field. I would try something like this (assuming you are using pnpjs)
import * as React from "react";
import { sp } from "#pnp/sp/presets/all";
// hello world react component
export const HelloWorld = () => {
const uploadFile = async (evt) => {
const file: File = evt.target.files[0];
// upload to the root folder of site assets in this demo
const assets = await sp.web.lists.ensureSiteAssetsLibrary();
const fileItem = await assets.rootFolder.files.add(file.name, file, true);
// bare minimum; probably you'll want other properties as well
const img = {
"serverRelativeUrl": fileItem.data.ServerRelativeUrl,
};
// create the item, stringify json for image column
await sp.web.lists.getByTitle("YourListWithImageColumn").items.add({
Title: "Hello",
YourImageColumn: JSON.stringify(img)
});
};
return (<div>
<input type='file' onChange={uploadFile} />
</div>);
};
#azarmfa,
The image file in fact did not store in the image field. The field just references its location. You could first upload the image file to a library (by default it will be site asset), then update the item like below:
let list = sp.web.lists.getByTitle("mylinks");
let json = {
"fileName": "Search_Arrow.jpg",
"serverUrl": "https://abc.sharepoint.com",
"serverRelativeUrl": "/sites/s01/Style%20Library/Images/Search_Arrow.jpg"
};
let jsonstr = JSON.stringify(json);
const i = await list.items.getById(3).update({
Title: "My New Tit",
img: jsonstr
});
BR

How do i share a video from react native to Instagram?

I'd like to share a video from my react native app to Instagram. I edit this video file so i'm not getting it directly from my camera roll, but i have a link to it locally which i've logged on my physical iPhone device below:
uri:
"private/var/mobile/Containers/Data/Application/(Long filename).mp4"
and i remove the "/private". What i'm trying to to with this is use 'Linking' from React Native :
shareToApp = (uri) => {
amendedURI = 'file://' + uri;
let encodedURL = encodeURIComponent(amendedURI);
let instagramURL = 'instagram://library?AssetPath=${' + encodedURL + '}';
return Linking.openURL(instagramURL);
}
but the screen where you share to 'Feed' or 'Stories' displays the last item in my gallery (pic or video), not the video i've passed as the 'uri'
Is there something here which prevents me from achieving this?
You can use react-native-share provided by react-native-community.
let shareOptions = {
url: `file://${this.state.files[0].data}`, //FetchBlob file path
type: `video/${file.extension}`, //file.extension contains the extension of the file
social: Share.Social.INSTAGRAM
};
await Share.shareSingle(shareOptions);

Is there an alternative for File() constructor for Safari and IE?

I am using the File() constructor for creating file object for uploading a blob file to the server. The following code works fine for Chrome, but fails for Safari and Internet Explorer.
image_url = new File([blob],file_name,{type: mimeString});
The code is breaking at this line and getting this error in console "FileConstructor is not a constructor" (evaluating 'new File([blob],file_name,{type: mimeString})')
Using the FileReader API is an alternative to this but I am not able to fix this issue.
I Suggest to use the blob api, I've found the same problem and I solved like that:
var html = <svg>whatever on svg </svg>
var fileName = "myfile.svg";
var blob = new Blob([html], {type: 'image/svg'});
blob.lastModifiedDate = new Date();
// var blobAttrs = {type: "image/svg"};
// var file = new File([html], fileName, blobAttrs);
var formData = new FormData();
formData.append("file",blob,fileName);
It is not a "file", but you can use it like it was.
According to web "Can I use" Safari does not support the new File() constructor. See this link http://caniuse.com/#feat=fileapi
So I think you have to either use FileReader or maybe use some of the polyfills listed here https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills
Especially this one could be useful for you https://github.com/mailru/FileAPI (I did not use it myself)
Also have a look at this SO answer What to use instead of FileReader for Safari?
If you can use ES6 classes:
class CustomFile extends Blob
{
constructor(blobParts, filename, options) {
super(blobParts, options);
this.name = filename || "";
if(options) {
this.lastModified = options.lastModified;
}
}
lastModified = 0;
name = "";
}
const blob = new Blob();
const fileObject = new CustomFile([blob],"myfile");
console.log(fileObject);
There is a File ponyfill on npm which works with modern module imports. This makes usage simple but you do need to import it in every module where you use new File().
import File from '#tanker/file-ponyfill';
const myFile = new File(['somefiledata'], 'example.txt', { type: 'text/plain'});

Uploading an image file to GAE datastore

Im trying to upload an image file to the GAE datastore using jQuery within CoffeScript.
The upload jQuery Post function I'm using is:
$.post "/uploadBTS?bts_spriteSheet=#{#bts_spritesheet_url}", (data) =>
console.log 'succsess'
#bts_spritesheet_url is obtained from the html5 File Api:
handleSpritesheetSelection = (evt) =>
files = evt.target.files
f = files[0]
reader = new FileReader()
# Closure to capture the file information.
reader.onload = ((theFile) =>
return (e) =>
#bts_spritesheet_url = e.target
)(f)
reader.readAsDataURL(f)
document.getElementById('upload_spritesheet').addEventListener('change', handleSpritesheetSelection, false)
The handeler in GAE for a post call to /uploadBTS is:
class UploadBTS(webapp2.RequestHandler):
def post(self):
# get information from form post upload
bts_spriteSheet = self.request.get('bts_spriteSheet')
# create database entry for uploaded image
bts_entry = Building_Tile_Sets()
bts_entry.image = db.Blob(bts_spriteSheet)
bts_entry.put()
and lastly the database I'm trying to put the information is a define thus:
# Database containg the bts
class Building_Tile_Sets(db.Model):
image = db.BlobProperty(default=None)
I get the following error when trying the upload:
POST http://localhost:8080/uploadBTS?bts_spriteSheet=[object%20FileReader]&bts_jason=[object%20Object]&bts_name=one 500 (OK)
Can anyone see where I'm going wrong?

Resources