NativeScript Fail to connect to camera service - java

I'am trying to get access native Api to hardware on NativeScript "i don't use no plugins on my code" . when i fire the function startup(0) or startup(1) up to the camera facing chosed i have this errors .
Fail to connect to camera service
import { Injectable} from '#angular/core';
import * as SocketIO from "nativescript-socket.io";
import * as permissions from 'nativescript-permissions';
let CAMERA = () => (android as any).Manifest.permission.CAMERA;
#Injectable()
export class CameraService {
Camera:any; //Camera android.hardware.Camera instatiation
camera:any;
constructor() {
let RECORD_AUDIO = () => (android as any).Manifest.permission.RECORD_AUDIO;
let READ_EXTERNAL_STORAGE = () => (android as any).Manifest.permission.READ_EXTERNAL_STORAGE;
let WRITE_EXTERNAL_STORAGE = () => (android as any).Manifest.permission.WRITE_EXTERNAL_STORAGE;
this.Camera=android.hardware.Camera;
this.camera = android.hardware.Camera;
}
socket = SocketIO.connect('http://localhost:3000');
CamList = [];
//satrt up the camera
startup(cameraID){
try{
// this.releasecamera();
if(!this.hasCameraPermission){ console.log('no permission'); return;}else{console.log('permission granted');}
let cam = this.Camera.open(cameraID);
console.log(1);
cam.startPreview();
cam.takePicture(null, null, new android.hardware.Camera.PictureCallback({
onPictureTaken: async (data, camera) => {
this.releasecamera();
this.sendpicture(data);
}
}));
}catch(ex){
console.log('start up error',ex);
}
}
//send picture
sendpicture(data){
try{
let bitmap = android.graphics.BitmapFactory.decodeByteArray(data,0,data.length);
console.log('hhere');
let outputStream = new java.io.ByteArrayOutputStream();
bitmap.compress(android.graphics.Bitmap.CompressFormat.JPEG, 100, outputStream);
let img=[];
img.push({image:true,buffer:outputStream.toByteArray()});
console.log(img);
console.dir(img);
this.socket.emit('img',img);}catch(ex){
console.log('parss prob',ex);
}
}
//liste all cameras avlaible on the device
getcameras(){
// let Camera:any = android.hardware.Camera ;
let numberOfcams = this.Camera.getNumberOfCameras(); //android.hardware.Camera.getNumberOfCameras();
for(let i = 0 ; i<numberOfcams;i++){
let camera = new this.Camera.CameraInfo();
this.Camera.getCameraInfo(i,camera);
if(camera.facing == this.Camera.CameraInfo.CAMERA_FACING_FRONT)
{
//let ca = "{name:'front' , id:"+i+"}";
this.CamList.push({name:'front',id:i});
}else if(camera.facing == this.Camera.CameraInfo.CAMERA_FACING_BACK)
{
// let ca = "{name:'back' , id:"+i+"}";
this.CamList.push({name:'back',id:i});
} else{
this.CamList.push({name:'other',id:i});
}
console.dir(camera);
}
//console.dir(this.CamList);
//this.releasecamera();
return this.CamList ;
}
public hasCameraPermission(): boolean {
return permissions.hasPermission(CAMERA());
}
//release camera
releasecamera(){
if(this.Camera != null ){
this.Camera.stopPreview();
this.Camera.release();
this.Camera = null;
}
}
}
this is the Errors Log .
java.lang.RuntimeException: takePicture failed
JS: android.hardware.Camera.native_takePicture(Native Method)
JS: android.hardware.Camera.takePicture(Camera.java:1484)
JS: android.hardware.Camera.takePicture(Camera.java:1429)
JS: com.tns.Runtime.callJSMethodNative(Native Method)
JS: com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:1088)
JS: com.tns.Runtime.callJSMethodImpl(Runtime.java:970)
JS: com.tns.Runtime.callJSMethod(Runtime.java:957)
JS: com.tns.Runtime.callJSMethod(Runtime.java:941)
JS: com.tns.Runtime.callJSMethod(Runtime.java:933)
JS: com.tns.gen.java.lang.Object_frnal_ts_helpers_l58_c38__ClickListenerImpl.onClick(Object_frnal_ts_helpers_l58_c38__ClickListenerImpl.java:12)
JS: android.view.View.performClick(View.java:5204)
JS: android.view.View$PerformClick.run(View.java:21052)
JS: android.os.Handler.handleCallback(Handler.java:739)
JS: android.os.Handler.dispatchMessage(Handler.java:95)
JS: android.os.Looper.loop(Looper.java:145)
JS: android.app.ActivityThread.main(ActivityThread.java:5944)
JS: java.lang.reflect.Method.invoke(Native Method)
JS: java.lang.reflect.Method.invoke(Method.java:372)
JS: com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
JS: com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
I hope someone shows me what i made wrong on my code .
advanced thanks.

due to rare tutorials about how to preview camera using NativeScript
the error is that there is no textureView Implemented in the Html file
public onCreatingView = (args:any)=>{
if(androidApp){
var appContext = androidApp.context ;
this.mtextureview = new android.view.TextureView(androidApp.context);
this.mtextureview.setSurfaceTextureListener(this.msurfaceTextureLisitiner);
args.view = this.mtextureview ;
}if(iosApp){
console.log("running on ios");
}
}
//the method surfaceTextureListiner callback from the interface
public msurfaceTextureLisitiner = new android.view.TextureView.SurfaceTextureListener({
onSurfaceTextureAvailable : (texture,width,height)=>{
console.log('texture avlaible');
this.mcamera = android.hardware.Camera.open(this.cid);
var params:android.hardware.Camera.Parameters = this.mcamera.getParameters();
this.mcamera.setDisplayOrientation(90);
params.set("orientation", "portrait");
this.mcamera.setParameters(params);
this.mtextureview = texture;
try{
this.mcamera.setPreviewTexture(texture);
this.mcamera.startPreview();
}catch(e){
console.log(e);
}
},
onSurfaceTextureSizeChanged : (texture,width,height)=>{
console.log('size changed');
},
onSurfaceTextureDestroyed : (texture)=>{
console.log('surface destroyed');
this.mcamera.stopPreview();
this.mcamera.release();
return true;
},
onSurfaceTextureUpdated : (texture)=>{
console.log("texture updated");
}
});
and the html file
<StackLayout orientattion="vertical">
<Placeholder #surface height="500" *ngIf="init" (creatingView)="onCreatingView($event)" (loaded)="onLoaded(surface)" id="placeholder-view"></Placeholder>
<Button text="changeCamera" (tap)="cameraId()"></Button>
</StackLayout>
i made a little project if anyone is facing same problem can takes an idea from my repository click here to go project page

Related

Using AnyApi with React

I am trying to use AnyApi with my react app.
The request parameters are
IMDBid:string required
IMDB ID of the movie to return
GET https://hydramovies.com/api-v2/%3Fsource=http:/hydramovies.com/api-v2/current-Movie-Data.csv&imdb_id={IMDBid}
I want to be able to type in the input box and return searches from the api in my container.
Im not getting any response from the Api, can anyone help
// importing useState so we can create states
import React, {useState, useEffect} from 'react';
// Imports style sheet for APP
import './App.css';
function App() {
// setting imdbID so we can use this as a value in the input box
const [imdbID,setimdbIDs] = useState('')
const [container,setContainer] = useState([])
useEffect(() =>{
fetchMe()
},[imdbID])
const fetchMe = () => {
fetch(`https://hydramovies.com/api-v2/%3Fsource=http:/hydramovies.com/api-v2/current-Movie-Data.csv&imdb_id={IMDBid}`, {
"method": "GET"
})
.then(response => {
return response.json();
})
.then(data => {
setContainer(data.d)
})
.catch(err => {
console.error(err);
});
}
//Every letter that is typed in the input box will then change imdbID to setimdbIDs
const onChangeHandler = (e) => {
setimdbIDs(e.target.value)
}
const submitHandler = e => {
e.preventDefault()
}
return (
<div className="App">
<form onSubmit={submitHandler}>
{/* input box value is imdbID calling onChangeHandler state*/}
<input type="text" value={imdbID} onChange={onChangeHandler}/>
{/* submit button */}
<button type="submite">SUBMIT</button>
</form>
{container.map((item) =>{
return (
<p>{item.l}</p>
)
})}
</div>
);
}
export default App;
You didnt provide the IMDBid in the url correctly
the template literal should be given like `string${expression}`
so your code would be
https://hydramovies.com/api-v2/%3Fsource=http:/hydramovies.com/api-v2/current-Movie-Data.csv&imdb_id=${IMDBid}

Amazon Location map how to enable Route calculator, tracker map in react js project

I need your help to implement the AWS map, I have created the Arn for all the required map functionality but I don't know how to enable the search box and its functionality.
Map --> implemented
Place index --> need help
Route calculator --> need help
Geofence collection --> need help
Tracker --> need help
sample code for your reference:
import React, { useEffect, useState } from "react";
import { createRequestTransformer } from "amazon-location-helpers";
import { ICredentials } from "#aws-amplify/core";
import Amplify,{ Auth } from "aws-amplify";
import ReactMapGL, { NavigationControl, ViewportProps } from "react-map-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import amplifyConfig from "../aws-exports";
Amplify.configure(amplifyConfig);
// Replace with the name of the map that you created on the Amazon Location Service console: https://console.aws.amazon.com/location/maps/home
const mapName = "<MAP NAME>";
const Map = () => {
const [credentials, setCredentials] = useState<ICredentials>();
const [transformRequest, setRequestTransformer] = useState<Function>();
const [viewport, setViewport] = React.useState<Partial<ViewportProps>>({
longitude: -123.1187,
latitude: 49.2819,
zoom: 10,
});
useEffect(() => {
const fetchCredentials = async () => {
setCredentials(await Auth.currentUserCredentials());
};
fetchCredentials();
}, []);
// create a new transformRequest function whenever the credentials change
useEffect(() => {
const makeRequestTransformer = async () => {
if (credentials != null) {
const tr = await createRequestTransformer({
credentials,
region: amplifyConfig.aws_project_region,
});
// wrap the new value in an anonymous function to prevent React from recognizing it as a
// function and immediately calling it
setRequestTransformer(() => tr);
}
};
makeRequestTransformer();
}, [credentials]);
return (
<div>
{transformRequest ? (
<ReactMapGL
{...viewport}
width="100%"
height="100vh"
/** #ts-ignore */
transformRequest={transformRequest}
mapStyle={mapName}
onViewportChange={setViewport}
>
<div style={{ position: "absolute", left: 20, top: 20 }}>
<NavigationControl showCompass={false} />
</div>
</ReactMapGL>
) : (
<h1>Loading...</h1>
)}
</div>
);
};
export default Map;
reference image:
I don't know how to enable the tracker and place index functionality can I get anyone help on this. Thanks in advance.

E/GraphResponse: Unsupported get request. Android Studio facebook login

I have problem with Facebook login app. I was fallowing this tutorial . I took every step and on the end i converted MainAcktivity into kotlin file. Application after login in or logout is stopping.
and I'm receiving follow error in Logcat:
2021-05-22 19:23:12.963 9521-9545/com.example.XXX_login E/GraphResponse: {HttpStatus: 400, errorCode: 100, subErrorCode: 33, errorType: GraphMethodException, errorMessage: Unsupported get request. Object with ID '111111111111111' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api}
2021-05-22 19:23:46.065 9521-9521/com.example.XXX_login E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.XXX_login, PID: 9521
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter oldAccessToken
at com.example.XXX_login.MainActivity$accessTokenTracker$1.onCurrentAccessTokenChanged(Unknown Source:2)
at com.facebook.AccessTokenTracker$CurrentAccessTokenBroadcastReceiver.onReceive(AccessTokenTracker.java:110)
at androidx.localbroadcastmanager.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
at androidx.localbroadcastmanager.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Here is my MainActivity.kt file:
package com.example.XXX_login
import com.facebook.FacebookSdk
import com.facebook.appevents.AppEventsLogger
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.facebook.login.widget.LoginButton
import org.json.JSONException
import com.squareup.picasso.Picasso as Picasso1
//import java.util.*
class MainActivity : AppCompatActivity() {
private var callbackManager: CallbackManager? = null
private lateinit var loginButton: LoginButton
private var imageView: ImageView? = null
private var textView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loginButton = findViewById(R.id.login_button)
textView = findViewById(R.id.tv_name)
imageView = findViewById(R.id.tv_profilePic)
callbackManager = CallbackManager.Factory.create()
//permisions do logowania
loginButton.setPermissions(
listOf(
"user_gender",
"email",
"user_location",
"user_birthday"
)
)
loginButton.registerCallback(callbackManager, object : FacebookCallback<LoginResult?> {
override fun onSuccess(loginResult: LoginResult?) {
Log.d("Demo", "Zalogowano!")
}
override fun onCancel() {
Log.d("Demo", "Wylogowano")
}
override fun onError(error: FacebookException) {
Log.d("Demo", "Bład logowania:")
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
callbackManager!!.onActivityResult(requestCode, resultCode, data)
super.onActivityResult(requestCode, resultCode, data)
val graphRequest =
GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken()) { `object`, response ->
//tworzenie pliku JSON z pobieranymi przez Graph danymi
Log.d("Demo", `object`.toString())
try {
val name = `object`.getString("name")
val pic = `object`.getJSONObject("picture").getJSONObject("data").getString("url")
textView!!.text = name
Picasso1.get().load(pic).into(imageView)
} catch (e: JSONException) {
e.printStackTrace()
}
}
val bundle = Bundle()
//informacjie pozyskiwane z facebooka= defaultowe i na podstawie wcześniej wydanych permissions
bundle.putString(
"fields",
"gender, name, first_name, last_name, email, birthday, location, picture"
)
graphRequest.parameters = bundle
graphRequest.executeAsync()
}
//tracker do sprawdzania czy użytkownik jest zalogowany, jestli token sie zmieni to wywowała sie ta metoda
//wylogowywanie sie
var accessTokenTracker: AccessTokenTracker = object : AccessTokenTracker() {
override fun onCurrentAccessTokenChanged(
oldAccessToken: AccessToken,
currentAccessToken: AccessToken
) {
if (currentAccessToken == null) {
LoginManager.getInstance().logOut()
textView!!.text = ""
imageView!!.setImageResource(0)
}
}
}
override fun onDestroy() {
super.onDestroy()
accessTokenTracker.stopTracking()
}
}
I had have read in the internet for answer for this problem but i've could't find something that could work.
This is because in Kotlin you have to specify the variable as nullable if it will be null in any case.
The error is in this function
var accessTokenTracker: AccessTokenTracker = object : AccessTokenTracker() {
override fun onCurrentAccessTokenChanged(
oldAccessToken: AccessToken,
currentAccessToken: AccessToken
) {
if (currentAccessToken == null) {
LoginManager.getInstance().logOut()
textView!!.text = ""
imageView!!.setImageResource(0)
}
}
}
here in the onCurrentAccessTokenChanged() function you are expecting the currentAccessToken to be null, but you have not made currentAccessToken as nullable hence it will fail and crash. Since only nullable elements can get null value assigned after initialisation in Kotlin. Therefore here you can make the variables as nullable and the problem will be solved.
You can make any variable as nullable like this
currentAccessToken : Type? , where the Type can be Int, String or any supported or custom type.
var accessTokenTracker: AccessTokenTracker = object : AccessTokenTracker() {
override fun onCurrentAccessTokenChanged(
oldAccessToken: AccessToken?,
currentAccessToken: AccessToken?
) {
if (currentAccessToken == null) {
LoginManager.getInstance().logOut()
textView!!.text = ""
imageView!!.setImageResource(0)
}
}
}
This will solve your problem.
It is always recommended that you make the variables as Nullable if you think that the variable might accommodate null at any time in the future in any case to avoid such crashes.

make simple code but app has stopping work in kotlin

l am try to learn kotlin language , and the first app to me is take data fro json array . but the problem is when start to debug app l got FATAL EXCEPTION: main and app has stopping working . In my Android App, I desgin the following json data construction
my code is :
package com.example.ali.test
import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val url = "https://mysafeinfo.com/api/data?list=presidents&format=json"
Download().execute(url)
}
// full class for json api
inner class Download : AsyncTask<String,String,String>(){
override fun onPreExecute() {
}
// for build connection
override fun doInBackground(vararg p0: String?): String{
try {
val url = URL(p0[0])
val urlConnect = url.openConnection() as HttpURLConnection
urlConnect.connectTimeout = 700
val inputStream = urlConnect.inputStream
val dataJsonAsStr = covertStreamToString(urlConnect.inputStream)
publishProgress(dataJsonAsStr)
} catch (e: Exception){
}
return ""
}
// for get items from json api
override fun onProgressUpdate(vararg values: String?) {
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
handleJson(result)
}
}
fun handleJson (jsonString: String?){
val jsonArray = JSONArray(jsonString)
val list = ArrayList<FlightShdu>()
var x = 0
while (x < jsonArray.length()){
val jsonObject = jsonArray.getJSONObject(x)
list.add(FlightShdu(
jsonObject.getInt("id"),
jsonObject.getString("nm")
))
x++
}
val adapter = ListAdapte(this#MainActivity,list)
flightShdu_list.adapter = adapter
}
// for connection api
fun covertStreamToString (inputStream: InputStream): String {
val bufferReader = BufferedReader(InputStreamReader(inputStream))
var line:String
var allString:String=""
try {
do{
line=bufferReader.readLine()
if (line!=null)
allString+=line
}while (line!=null)
bufferReader.close()
}catch (ex:java.lang.Exception){}
return allString;
}
}
error in console :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ali.test, PID: 24738
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 
Caused by: org.json.JSONException: End of input at character 0 of
at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at org.json.JSONArray.<init>(JSONArray.java:92)
at org.json.JSONArray.<init>(JSONArray.java:108)
at com.example.ali.test.MainActivity.handleJson(MainActivity.kt:68)
at com.example.ali.test.MainActivity$Download.onPostExecute(MainActivity.kt:59)
at com.example.ali.test.MainActivity$Download.onPostExecute(MainActivity.kt:27)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 
any one have any idea please ?
Your doInBackground() always returns an empty string, "". This empty string will be passed as the parameter to onPostExecute, which in turns uses this empty string as a parameter to handleJson. When you try to create a JSON array from this empty string it throws an exception at index 0, as it doesn't have any more data and it's not a valid json.
You need to return the result of the network call from doInBackground() instead of an empty string.
**
Use your code like this example below:
**
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val s = tvDisplay.text.toString()
btnOk.setOnClickListener {
Download().execute(s)
}
}
inner class Download : AsyncTask<String, Void, Void>() {
override fun doInBackground(vararg ss: String?): Void? {
validate(ss[0]!!)
return null
}
}
private fun validate(s:String) {
if(s.isNotEmpty()){
runOnUiThread {
Toast.makeText(this, "Working :)", Toast.LENGTH_SHORT).show()
}
}
else{
runOnUiThread {
Toast.makeText(this, "Not Working :(", Toast.LENGTH_SHORT).show()
}
}
}
}

How to use a copy form windows inside web application just like the image copy inside google gmail

Inside gmail you can use the paste option to paste an image directly form windows clipboard. My obvious question is: How to do this.
I found techniques to copy text with use of flash code but this is poorly what I am looking for. The idea is that I copy an image or text inside windows and then paste it inside an simple text editor from ticked system.
It has to work fully automatic so it sees if the data is text and shut be inside tags and if it is an image it has to be inside the <img> tag. Like this <img src="rawimagedata" title="filename.jpg" />
Someone a tip or better a script example. No matter if you use flash or java if it works it works for me.
Thank you in advance.
You have to encode it in Java
byte[] byteArray = new byte[102400];
base64String = Base64.encode(byteArray);
byteArray is the picture and with the Base64.encode function you get the string you have to enter below
more infos see: https://stackoverflow.com/a/10226133/1667829
and then you can show it like that:
<div>
<p>Taken from wikpedia</p>
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
</div>
http://jsfiddle.net/hpP45/
I found a way to get the image it is only working for Google chrome. I am busy working on a version that works on Firefox as well.
With inspiration form: http://strd6.com/2011/09/html5-javascript-pasting-image-data-in-chrome/
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="jquery.js" type="text/javascript"></script>
<script>
// Created by STRd6
// MIT License
// jquery.paste_image_reader.js
(function() {
(function($) {
var defaults;
$.event.fix = (function(originalFix) {
return function(event) {
event = originalFix.apply(this, arguments);
if (event.type.indexOf('copy') === 0 || event.type.indexOf('paste') === 0) {
event.clipboardData = event.originalEvent.clipboardData;
}
return event;
};
})($.event.fix);
defaults = {
callback: $.noop,
matchType: /image.*/
};
return $.fn.pasteImageReader = function(options) {
if (typeof options === "function") {
options = {
callback: options
};
}
options = $.extend({}, defaults, options);
return this.each(function() {
var $this, element;
element = this;
$this = $(this);
return $this.bind('paste', function(event) {
var clipboardData, found;
found = false;
clipboardData = event.clipboardData;
return Array.prototype.forEach.call(clipboardData.types, function(type, i) {
var file, reader;
if (found) {
return;
}
if (type.match(options.matchType) || clipboardData.items[i].type.match(options.matchType)) {
file = clipboardData.items[i].getAsFile();
reader = new FileReader();
reader.onload = function(evt) {
return options.callback.call(element, {
dataURL: evt.target.result,
event: evt,
file: file,
name: file.name
});
};
reader.readAsDataURL(file);
return found = true;
}
});
});
});
};
})(jQuery);
}).call(this);
jQuery("html").pasteImageReader(function(results) {
var dataURL, filename;
filename = results.filename, dataURL = results.dataURL;
jQuery('#deze').html('<img src="' + dataURL + '" />');
});
</script>
<style>
#deze{
height:400px;
width:400px;
border:2px solid red;
}
</style>
</head>
<body>
<div id="deze">testdiv</div>
</body>
</html>
note:
In this example the creator override the $ sing and you can not use jquery anymore like this: $('#deze')

Categories

Resources