Looking how vue-upload-component works (https://lian-yue.github.io/vue-upload-component/#/documents) on events when
file is uploaded I see structure of avatarFiles array with uploaded file:
<file-upload
ref="upload"
v-model="avatarFiles"
post-action="/post.method"
put-action="/put.method"
#input-file="inputFile"
#input-filter="inputFilter"
:multiple="false"
class="btn btn-outline-danger btn-sm"
>
Upload avatar
</file-upload>
I do not see width/height of any uploaded file. If there is a way to add this info too?
Or some other vuejs way to get width/height of any uploaded file ?
vuejs 2.6
I try to check event when image is uploaded with:
MODIFIED :
watch:{
avatarFiles(file){
console.log("-1 avatarFiles file::")
console.log( file )
var image = new FileReader();
console.log("-2 avatarFiles image::")
console.log( image )
image.onload = () => {
console.log("-3 avatarFiles file::")
console.log( file )
console.log(`the image dimensions are ${img.width}x${img.height}`);
}
}
},
But image.onload is not triggered and in console I see some error message:
https://imgur.com/a/40epviI
What is wrong ?
Try to watch your avatarFiles model, then read file using FileReader.
example codes:
watch:{
avatarFiles(file){
var image = new FileReader();
image.onload = () => {
console.log(`the image dimensions are ${image.width}x${image.height}`);
}
}
}
Related
I got a component that let's the user upload a profile picture with a preview before sending it off to cloudinary.
<template>
<div>
<div
class="image-input"
:style="{ 'background-image': `url(${person.personData.imagePreview})` } "
#click="chooseImage"
>
<span
v-if="!person.personData.imagePreview"
class="placeholder"
>
<i class="el-icon-plus avatar-uploader-icon"></i>
</span>
<input
type="file"
ref="fileInput"
#change="previewImage"
>
</div>
</div>
</template>
The methods to handle the preview:
chooseImage() {
this.$refs.fileInput.click()
},
previewImage(event) {
// Reference to the DOM input element
const input = event.target;
const files = input.files
console.log("File: ", input.files)
if (input.files && input.files[0]) {
this.person.personData.image = files[0];
const reader = new FileReader();
reader.onload = (e) => {
this.person.personData.imagePreview = e.target.result;
}
// Start the reader job - read file as a data url (base64 format)
reader.readAsDataURL(input.files[0]);
}
},
This works fine, except for when the user fetches a previous project from the DB. this.person.personData.imagePreview get's set to something like https://res.cloudinary.com/resumecloud/image/upload/.....id.jpg Then when the user wants to change his profile picture, he is able to select a new one from his local file system, and this.person.personData.imagePreview is read again as a data url with base64 format. But the preview doesn't work. Only when I change routes back and forth, the correct image selected by the user is displayed.
Like I said in the comment on my post. Turns out I'm an idiot. When displaying the preview, I used this.person.personData.imagePreview . When a user fetches a project from the DB, I just did this.person.personData = response.data. That works fine, apart from the fact that I had a different name for imagePreview on my backend. So I manually set it on the same load method when fetching from the DB like: this.person.personData.imagePreview = this.loadedPersonData.file. For some reason, that screwed with the reactivity of Vue.
I want to download my drawing on the React canvas as a jpeg image file to my desktop, and then pass it to a python file for classification. Can someone specify a code to download the React canvas drawing, or suggest a better way to implement the idea?
clearCanvas({nativeEvent}) {
var image = this.canvas.toDataURL("image/jpeg");
nativeEvent.href=image;
this.ctx.save("C:/Users/PrishitaRay/Pictures/Myimage.jpeg");
this.ctx = this.canvas.getContext('2d');
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
This function just clears the react canvas without downloading it first.
After reading your code, I'm not sure if its related to React. Therefore I'm going to give a non-react solution.
In case you have done some drawing on the canvas like my exampleDrawing function, then just call download function like this.
function exampleDrawing(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
}
function download(){
var canvas = document.getElementById("canvas");
var url = canvas.toDataURL("image/png");
var link = document.createElement('a');
link.download = 'filename.png';
link.href = url;
link.click();
}
exampleDrawing();
<canvas id="canvas" width="200" height="100">
</canvas>
<button onclick="download();">Download!</button>
What my download function do is to create a URL that contains the canvas's image, generate a link, and then click on it.
And of course you don't have to generate a button and click on it. Just call the download function whenever you want.
Download Canvas as Image in React (Js only): (React Class Components)
Download As Image Function: chartRef.canvas gives the canvas element, replace it with your Canvas element.
handleChartDownload = (chartRef) => {
const chartCanvas = chartRef.canvas;
if (chartCanvas) {
const url = chartCanvas.toDataURL("image/png");
const link = document.createElement("a");
link.download = "chart.png";
link.href = url;
link.click();
}
};
Graph Element: these elements comes under render() function.
Download Button:
<button
className="btn btn-light"
onClick={() => this.handleChartDownload(this.chartRef)}
>Download</button>
Graph: (here Scatter is ChartJsReact component, used for creating graphs)
<Scatter
ref={(reference) => (this.chartRef = reference)}
data={this.state.chartData}
options={this.state.chartOptions}
/>
This one I've been banging my head against for a few weeks now.
Scenario:
Let user generate an image out of layers they select
Convert image to canvas
Share image from canvas on facebook wall using share_open_graph (along with the image, a short text and title will be shared)
I've already had a solution in place using publish_actions but that was recently removed from the API and is no longer available.
I am using js and html for all code handling.
The issue is that I can generate a png image from the canvas but that is saved as base64 and share_open_graph doesn't allow this type of image, it needs a straight forward url such as './example.png'. I have tried using several approaches and with canvas2image, converting and saving image using file-system but all of these fail.
Does anyone have similar scenario and possible solution from April/May 2018 using share_open_graph ?
My current code looks like this - it fails at the image conversion and save to a file (Uncaught (in promise) TypeError: r.existsSync is not a function at n (file-system.js:30)). But I am open to different solutions as this is clearly not working.
html2canvas(original, { width: 1200, height: 628
}).then(function(canvas)
{
fb_image(canvas);
});
var fb_image = function(canvas) {
canvas.setAttribute('id', 'canvas-to-share');
document.getElementById('img-to-share').append(canvas);
fbGenerate.style.display = 'none';
fbPost.style.display = 'block';
var canvas = document.getElementById('canvas-to-share');
var data = canvas.toDataURL('image/png');
var encodedPng = data.substring(data.indexOf(',') + 1, data.length);
var decodedPng = base64.decode(encodedPng);
const buffer = new Buffer(data.split(/,\s*/)[1], 'base64');
pngToJpeg({ quality: 90 })(buffer).then(output =>
fs.writeFile('./image-to-fb.jpeg', output));
var infoText_content = document.createTextNode('Your image is being
posted to facebook...');
infoText.appendChild(infoText_content);
// Posting png from imageToShare to facebook
fbPost.addEventListener('click', function(eve) {
FB.ui(
{
method: 'share_open_graph',
action_type: 'og.shares',
href: 'https:example.com',
action_properties: JSON.stringify({
object: {
'og:url': 'https://example.com',
'og:title': 'My shared image',
'og:description': 'Hey I am sharing on fb!',
'og:image': './image-to-fb.jpeg',
},
}),
},
function(response) {
console.log(response);
}
);
});
};
I am using the latest version of KeystoneJS and have a form working to add a record to the database.
I'm having trouble getting image uploads to work.
My model conatains:
heroImage: { type: Types.CloudinaryImage, autoCleanup : true },
My form includes:
<input type="file" accept="image/*" id="heroImage" name="heroImage_upload" className='field-upload'>
and my middleware for saving the form simply includes:
view.on('post', {action: 'save'}, function(next)
{
var newProperty = new Property.model(req.body);
console.log(newProperty);
newProperty.save(function(err, body)
{});
});
which works great for all field's except the file upload.
I've tried adding:
newProperty.heroImage = req.files['heroImage'];
which leaves heroImage as null.
I also tried creating a cloudinaryImage but this causes an error:
var img = new CloudinaryImage(req.files['heroImage']);
It all works fine when I use the KeystoneJS admin dashboard to upload images. Can someone please explain how I should use the cloudinaryImage field type in my own form?
Thanks
Not sure if this will help, but there is a note at the bottom of the docs:
http://keystonejs.com/docs/database/#fieldtypes-cloudinaryimage
"Remember that if you are uploading images to a CloudinaryImage field using an HTML form, you need to specify enctype="multipart/form-data" in your form tag."
Have you included that in your form?
Update:
So, the following should work, assuming your model is called MyModel, and your form data uses the same object keys as your model. (i.e. the image for your heroImage field should be provided as heroImage in the POST data).
var MyModel = keystone.list('MyModel');
view.on('post', {action: 'save'}, function(next)
{
var item = new MyModel.model();
data = req.body;
item.getUpdateHandler(req).process(data, function(err) {
// Handle error
}
}
Keystone should then handle all the specific cloudinary stuff internally.
Here is a way to do it with cloudinary.v2
untested keystone
cloudinary.v2.uploader.upload(base64_file_data, (err, result) => {
var newMyModel = new MyModel.model(model_data);
newMyModel.image = result;
let updater = newMyModel.getUpdateHandler(req);
updater.process(newMyModel, {
fields: image
}, err => {...})
})
tested mongoose
cloudinary.v2.uploader.upload(base64_file_data, (err, result) => {
var newMyModel = new MyModel.model(model_data);
newMyModel.image = result;
newMyModel.save(err => {...})
})
I want to display Image and store Image on remote server.I am using Ibm Worklight Version 6.2.I Have gone through many links but didn't find the solution
My HTML Page code is
<fieldset style="height:auto;width:100% ">
<div id="Image" style="float:left;">
</div>
<div id ="delImage">
</div>
</fieldset>
and my Js Code is
uploadImage = function (){
navigator.camera.getPicture(onSuccessCallBack, onFailCallBack, {
quality: 50,
sourceType: Camera.PictureSourceType.CAMERA,
destinationType: Camera.DestinationType.FILE_URI
});
};
function onSuccessCallBack (imageData){
var img = document.createElement("img");
img.style.width = "60px";
img.style.height="60px";
img.src = imageData;
var Image = document.getElementById("Image");
Image.appendChild(img);
var delImg = document.createElement("img");
delImg.style.width = "60px";
delImg.style.height="60px";
delImg.src = "images/brws_gal.png";
var deleteImg = document.getElementById("delImage");
deleteImg.appendChild(delImg);
var invocationData = {
adapter : 'DisbursalRequestImageAdapter',
procedure : "uploadImageForDisbursal",
parameters : [ requestObject, sessionId, operationFlag,'','' ]
};
var options = {
timeout : timeout,
onSuccess : successCreateImg,
onFailure : failureCreateImg
};
WL.Client.invokeProcedure(invocationData, options);
};
Here, I am appending Dynamic Image in a div.
My Question is
I want to store the image to remote server using Http Adapter
I want to open the picture on the click of Picture.
I am not arrange the div vertically i.e. every time the photo is taken a new div should be created.
If you want to send an image to a remote server, you need to base64 encode the image and then send this string to be stored in the remote server's database.
If you want to then retrieve it you need to get the string and then decode the base64 string back to an image filetype and display the image in your HTML (the image should be stored in the device storage using Cordova APIs as you have demonstrated use of).
In fact, had you searched, the above is what you would've found in searches.