How To Access ngCordova Camera Image From Inside JavaScript - html

I am currently developing a photo-editing app with the Ionic Framework. At the moment, I have used an open-source JS Drag & Drop photo editor and have modified accordingly but I need to be able to access the image that the user creates with the ngCordova Camera plugin outside of the AngularJS and in a separate script with only JS.
I've decided to take on the ( angular.element(document.getElementById('editor')).scope(). ) approach but have come to no avail.
I'm starting to think that isn't going to be possible but that's why I came here to give it a final shot.
Here's some code from the editor. Yoda is the background image which works when set to a locally stored image.
window.onload = function() {
//THIS IS WHERE WE WILL ACCESS THE IMAGE GENERATED BY ngCamera
var sources = {
yoda: angular.element(document.getElementById('editor')).scope().pictureUrl
};
loadImages(sources, initStage);
};
Below is where we take the picture and assign its url to $scope.pictureUrl. Ignore the adding to array part, that is for syncing the images to Firebase.
$cordovaCamera.getPicture(options)
.then(function(imageData) {
syncArray.$add({image: imageData});
$scope.pictureUrl= 'data:image/jpeg:base64,' + data
.then(function() {
alert("Image has been uploaded");
});
}, function(error) {
console.error(error);
});
};
Pastebin for the whole app.js file: http://pastebin.com/8A8C4hL3
In brief, I am looking for a way to access an image created by ngCordova's Camera plugin inside of some actual JS and outside of the AngularJS used by the Ionic Framework.

If its just you want your image in an external js file, then you can try to store the image in localStorage like
$cordovaCamera.getPicture(options).then(function(imageData) {
localStorage.setItem('myBase64Image', ("data:image/jpeg;base64," + imageData));
}, function(err) {
console.log('error in camera then');
// error
});
Then in your external js file You can access your base64 image like.
localStorage.getItem('myBase64Image')
Hope this helps.

Related

Make isotope wait till api data is loaded - nuxt js

I'm running a nuxtjs app which displays data from wordpress. On my project overview page I want to have the images of the different projects displayed as masonry with isotope and filtering. When I open the website on root and navigate to the project page (/project) everything is displayed correctly. When I reload the page or type in the URL manually, the layout is crashed. After some error handling I found out that on page reload isotope wants to layout the unloaded project data.
On page enter - "projekte geladen."
On reload / manually - "keine projekte".
Code:
<script>
/* eslint-disable */
let Isotope;
let imagesLoaded;
if (process.client) {
Isotope = require('isotope-layout');
imagesLoaded = require('imagesloaded')
}
export default {
mounted() {
this.isCaseStudy();
this.isotope();
},
computed: {
page(){
//return this.$store.getters.filterProject;
return this.pages.find(page => page.id === 110)
},
pages(){
return this.$store.state.pages;
},
projects(){
return this.$store.state.projects;
},
},
created(){
this.$store.dispatch("getPages");
this.$store.dispatch("getProjects");
},
methods: {
isCaseStudy(){
$(".item").each(function(){
$(this).has('img.case-studyImg').addClass('case-study');
});
},
isotope() {
console.log("isotope wird ausgeführt");
if(this.projects.length != 0){
console.log("projekte geladen!")
let iso = new Isotope('.items', {
itemSelector: '.item',
masonry: {
columnWidth: '.grid-sizer'
}
});
imagesLoaded(".items").on( 'progress', function() {
// layout Isotope after each image loads
console.log("each image loaded");
iso.layout();
});
}else{
console.log("keine projekte");
}
},
filterItems(selector) {
let oldActive = $(".filters .btn-primary").first();
console.log(oldActive);
if(oldActive.hasClass(selector)){
return;
}
let currentActive = $(".filters a." + selector).first();
console.log(currentActive);
currentActive.removeClass("btn-default").addClass("btn-primary");
oldActive.removeClass("btn-primary").addClass("btn-default");
iso.arrange({filter: `.${selector}`});
}
}
}
</script>
So on reload the function this.isotope() is loaded before the projects() from computed loaded I believe.
How can I accomplish that isotope loads when the projects are loaded if thats the real problem for this...
In your case when dispatching actions in the created() hook the actions just start, but you do not know when they finish, the rest of the code keeps executing. In other words, by the time this.isotope() is called, your projects are not in the store yet.
Since you're using Nuxt, probably the best approach would be to use the asyncData hook. Using that, on first load (refreshing the page, or entering the url manually) the code inside asyncData will be executed on the server, so you're sure that the component will have the API data before rendering. It's also a faster approach, as you're leveraging the built-in nuxt SSR.
Another option would be to use async/await. You can take a look here how that would look. You might end up with something like this:
beforeMount() {
this.$store.dispatch('getPages');
this.$store.dispatch('getProjects');
},
where the getPages and getProjects functions in the store use async/await
async getProjects(vuexContext) {
const projects = await this.$axios.$get('http://yourapi.com/projects')
commit('SET_PROJECTS', projects)
}

Problem with Firebase Image Resize extension [duplicate]

I am following a tutorial to resize images via Cloud Functions on upload and am experiencing two major issues which I can't figure out:
1) If a PNG is uploaded, it generates the correctly sized thumbnails, but the preview of them won't load in Firestorage (Loading spinner shows indefinitely). It only shows the image after I click on "Generate new access token" (none of the generated thumbnails have an access token initially).
2) If a JPEG or any other format is uploaded, the MIME type shows as "application/octet-stream". I'm not sure how to extract the extension correctly to put into the filename of the newly generated thumbnails?
export const generateThumbs = functions.storage
.object()
.onFinalize(async object => {
const bucket = gcs.bucket(object.bucket);
const filePath = object.name;
const fileName = filePath.split('/').pop();
const bucketDir = dirname(filePath);
const workingDir = join(tmpdir(), 'thumbs');
const tmpFilePath = join(workingDir, 'source.png');
if (fileName.includes('thumb#') || !object.contentType.includes('image')) {
console.log('exiting function');
return false;
}
// 1. Ensure thumbnail dir exists
await fs.ensureDir(workingDir);
// 2. Download Source File
await bucket.file(filePath).download({
destination: tmpFilePath
});
// 3. Resize the images and define an array of upload promises
const sizes = [64, 128, 256];
const uploadPromises = sizes.map(async size => {
const thumbName = `thumb#${size}_${fileName}`;
const thumbPath = join(workingDir, thumbName);
// Resize source image
await sharp(tmpFilePath)
.resize(size, size)
.toFile(thumbPath);
// Upload to GCS
return bucket.upload(thumbPath, {
destination: join(bucketDir, thumbName)
});
});
// 4. Run the upload operations
await Promise.all(uploadPromises);
// 5. Cleanup remove the tmp/thumbs from the filesystem
return fs.remove(workingDir);
});
Would greatly appreciate any feedback!
I just had the same problem, for unknown reason Firebase's Resize Images on purposely remove the download token from the resized image
to disable deleting Download Access Tokens
goto https://console.cloud.google.com
select Cloud Functions from the left
select ext-storage-resize-images-generateResizedImage
Click EDIT
from Inline Editor goto file FUNCTIONS/LIB/INDEX.JS
Add // before this line (delete metadata.metadata.firebaseStorageDownloadTokens;)
Comment the same line from this file too FUNCTIONS/SRC/INDEX.TS
Press DEPLOY and wait until it finish
note: both original and resized will have the same Token.
I just started using the extension myself. I noticed that I can't access the image preview from the firebase console until I click on "create access token"
I guess that you have to create this token programatically before the image is available.
I hope it helps
November 2020
In connection to #Somebody answer, I can't seem to find ext-storage-resize-images-generateResizedImage in GCP Cloud Functions
The better way to do it, is to reuse the original file's firebaseStorageDownloadTokens
this is how I did mine
functions
.storage
.object()
.onFinalize((object) => {
// some image optimization code here
// get the original file access token
const downloadtoken = object.metadata?.firebaseStorageDownloadTokens;
return bucket.upload(tempLocalFile, {
destination: file,
metadata: {
metadata: {
optimized: true, // other custom flags
firebaseStorageDownloadTokens: downloadtoken, // access token
}
});
});

How can upload a image from system to angular project without browsing the image instead of clicking one button?

My aim is to upload a image from local system (means a specified folder) into my angular project ,Without browsing and using a button function i need to get the image into my project,,So when the card reader reads the card automatically a folder would generate in c , i wanna take image from there
anyone know about it?
Try to insert this piece of code from here you can upload files from your local system.
selectAFile: File = null;
onFileSelection(event) {
this.selectAFile = <File>event.target.files[0]
}
now upload function and select a storage place
upload() {
const fd = new FormData();
fd.append('image', this.selectAFile, this.selectAFile.name);
this.http.post('storageplacelink', fd).subscribe(res => {
console.log(res)
})
}

Is there any way I can add or set the sandbox keywords in Google Web App?

I've added a button into my Google Web App that when clicked, dynamically creates a new file in my Drive and downloads it to my local machine. I'm looking for a way to add the key word 'allow-downloads-without-user-activation' to the iframe so that it will continue to work after drive-by downloads are deprecated.
Currently, the console is giving me a warning to add 'allow-downloads-without-user-activation' since it will be removed in M74. Background details: https://www.chromestatus.com/feature/5706745674465280
function doGet(e) {
return HtmlService.createTemplateFromFile('MainPage').evaluate();
}
The code above is how I currently display the web app, and I could not find any way to add sandbox keyword from there. Is there any way to add this keyword to the iframe in Google App Script?
Edit:
This is the code in my html file.
$('#downloadBtn').click( function() {
$('#downloadBtnLabel').html('Preparing file...');
$('#Spinner').css('display','block');
google.script.run.withSuccessHandler(downloadFile).getTempLink();
});
function downloadFile(createdSpreadsheetId) {
var dlink = document.createElement('a');
dlink.download = name;
dlink.href = 'https://docs.google.com/spreadsheets/d/' + createdSpreadsheetId + '/export?exportFormat=xlsx';
dlink.onclick = function(e) {
var that = this;
setTimeout(function() {
window.URL.revokeObjectURL(that.href);
}, 1500);
};
dlink.click();
dlink.remove();
$('#downloadBtnLabel').html('Download');
$('#Spinner').css('display','none');
}
Parts of the above code is from https://stackoverflow.com/a/35251739 (special thanks to the author), which is working perfectly, just with the warnings in console.

Chrome Extension: Insert a clickable image using a content script

I know hat it is possible, but I am not quite sure how to do it the 'right' way, as to ensure there are no conflicts.
I came across this question: Cannot call functions to content scripts by clicking on image . But it is so convoluted with random comments that it's hard to understand what the corrected way was.
Use case:
Html pages have a div on the page where they expect anyone using the Chrome extension to inject a picture. When users click on he picture, I want to somehow notify an event script. So I know I need to register a listener so the code inserted messages the event script.
Can I get some indication on what code to inject through the content script? I saw that sometimes injecting jquery directly is advised.
I am trying to avoid having the html page to post a message to itself so it can be intercepted. Thanks
With the help of Jquery something like this would capture the image onclick event and allow you to pass a message to a background page in the Chrome Extension:
$("img").click(function(){
var imageSrc = $(this).attr("src");
//Post to a background page in the Chrome Extension
chrome.extension.sendMessage({ cmd: "postImage", data: { imgSrc: imageSrc } }, function (response) {
return response;
});
});
Then in your background.js create a listener for the message:
chrome.extension.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.cmd == "postImage") {
var imageSrc = request.data.imgSrc;
}
});