Upload Image Width and Height get in react - reactjs

I am new to React and react hook I want to upload an image from anywhere but I want to know the width and height of a select image before storing it in the database. I want to store the original image metadata width and height. anyone can help me

One solution can be to use FileReader, something like this should work:
const image = new Image();
let fr = new FileReader();
fr.onload = function() {
if (fr !== null && typeof fr.result == "string") {
image.src = fr.result;
}
};
fr.readAsDataURL(inputFile);
image.onload = async function() {
const width = image.width;
};
You can take a look here: https://github.com/toncic/Image-Classification/blob/master/src/Components/ImageClassification.tsx#L45

Related

How do I preload my image array via javascript

I would like to have some advice on how to best preload my image array in javascript.
I've been reading some other solutions but as someone new I'm having some problem on how to implement them in my existing code.
Thank you.
const layerImage = {
1:'https://plateau.ar/story/scroll/images/Video401.png',
2:'https://plateau.ar/story/scroll/images/Video402.png',
3:'https://plateau.ar/story/scroll/images/Video403.png',
4:'https://plateau.ar/story/scroll/images/Video404.png',
5:'https://plateau.ar/story/scroll/images/Video405.png',
68:'https://plateau.ar/story/scroll/images/Video468.png',
69:'https://plateau.ar/story/scroll/images/Video469.png',
70:'https://plateau.ar/story/scroll/images/Video470.png',
71:'https://plateau.ar/story/scroll/images/Video471.png',
72:'https://plateau.ar/story/scroll/images/Video472.png',
73:'https://plateau.ar/story/scroll/images/Video473.png',
74:'https://plateau.ar/story/scroll/images/Video474.png',
}
function checkScroll() {
const y = window.scrollY;
const scrollPixels = Math.min(Math.floor(y/100) + 1, 74);
const imageToUse = layerImage[scrollPixels];
// Change the background image
$('.imageBox').css('background-image', `url('${imageToUse}')`);
}
$(document).ready(()=>{
$(window).scroll(()=>{
checkScroll();
})
})

How to create object of image in Reactjs

I want to get rendered height and width of the image before loading so I have created an object of image and trying to get height, width by onload method.
Below is my code snippet:
var imgUrl = "https://www.sammobile.com/wp-content/uploads/2019/03/keyguard_default_wallpaper_green-405x405.png";
var imgHeight = 0;
var imgWidth = 0;
var Im = new Image();
Im.src = imgUrl;
Im.onload = () => (imgHeight = Im.height);
But I am getting an error while creating the image object.
Image is not a constructor
How can I investigate this?
I don’t have enough points to comment but there is nothing wrong with your snippet.
checked browser compatibility and it’s very good.
You don’t have this API for some reason, might worth check your bundler for answers.
As pointed out by #mstrk there's nothing wrong with your script, however, if your runtime (your browser) somehow doesn't know how to construct the image via new Image() you can create one via
document.createElement('img')
Here's the snippet printing width / height in the console when image loads
var imgUrl = "https://www.sammobile.com/wp-content/uploads/2019/03/keyguard_default_wallpaper_green-405x405.png";
var imgHeight = 0;
var imgWidth = 0;
var Im = document.createElement('img');
Im.src = imgUrl;
Im.onload = () => {
imgHeight = Im.height;
imgWidth = Im.width;
console.log(imgWidth, imgHeight);
}

How do I add an object to React-Three outside componentDidMount?

I have run the React samples for Three.js, but can't seem to work out how to add an object (mesh, geometry) outside componentDidMount.
I've tried to add new objects, dispose of previous objects, update bufferGeometry
componentDidMount() {
const width = this.mount.clientWidth
const height = this.mount.clientHeight
//ADD SCENE
this.scene = new THREE.Scene()
//ADD CAMERA
this.camera = new THREE.PerspectiveCamera(
75,
width / height,
0.1,
1000
)
this.camera.position.z = 4
//ADD RENDERER
this.renderer = new THREE.WebGLRenderer({ antialias: true })
this.renderer.setClearColor('#000000')
this.renderer.setSize(width, height)
this.mount.appendChild(this.renderer.domElement)
//ADD CUBE
const geometry = new THREE.BoxGeometry(12, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: '#FFFF81' })
this.cube = new THREE.Mesh(geometry, material)
this.scene.add(this.cube)
this.start()
}
---------------------------------------------
addIT(){
const geometry3 = new THREE.BoxBufferGeometry(2,3, 1)
const material3 = new THREE.MeshBasicMaterial({ color: '#00FF81' })
this.cube3 = new THREE.Mesh(geometry3, material3)
this.scene.add(this.cube3)
this.start()
}
What I'd like to get to is for a react event to be able to add or remove an object from the scene.
At the moment, I get nothing.
Any thoughts would be appreciated.
I eventually worked out what was happening. Cube3 wasn't being added and an error was being thrown. I placed a stop render in addIt added the object and then started the render again.

how to fix this Error Cannot use the same canvas during multiple render() operations

I am using canvas in react and rendering pdf's as images using the canvas.
Now, when I get new data i.e another pdf get's added, then
again have to use the canvases for that.
I am not sure how to fix this error or how to remove the canvas or even clear the canvas before using it again.
Here's the relevant code:
pdfLoop = (item,index) => {
var that = this;
PDFJS.getDocument(item).then(function getPdfHelloWorld(pdf) {
//
// Fetch the first page
console.log('url is : ',item);
pdf.getPage(1).then(function getPageHelloWorld(page) {
var scale = 0.5;
var viewport = page.getViewport(scale);
let cref = 'canvas'+index;
let imgref ='img'+index;
console.log('cref no : ',cref);
console.log('img no : ',imgref);
// Prepare canvas using PDF page dimensions
//
var canvas = that.canvasRefs[cref];
//let imagez = that.imageRefs[imgref];
var context = canvas.getContext('2d');
context.globalcompositeoperation = 'source-over';
// context.fillStyle = "#fff";
//draw on entire canvas
//context.fillRect( 0, 0, canvas.width, canvas.height );
canvas.height = viewport.height;
canvas.width = viewport.width;
//imagez.src = canvas.toDataURL("image/png");
//
// Render PDF page into canvas context
//
//page.render({canvasContext: context, viewport: viewport});
var task = page.render({canvasContext: context, viewport: viewport})
task.promise.then(function(){
//console.log(canvas.toDataURL('image/png'));
let imgItem = {imgref:canvas.toDataURL('image/png'),page:index+1,rotate:0}
let newState = that.state.imgsrc;
newState[index] = imgItem;
//let newState = that.state.imgsrc.concat(imgItem);
that.setState({
imgsrc:newState
});
//imagez.src = canvas.toDataURL('image/png')
});
});
});
}
In case someone stumbles across this, the error message states the following Use different canvas or ensure previous operations were cancelled or completed.
When getting the document, if there already is a document, it has to be destroyed. I.e:
PDFJS.getDocument({ url: pdf_url }).promise
.then((pdf_doc) => {
if (this.pdf_doc) {
this.pdf_doc.destroy();
}
this.pdf_doc = pdf_doc;
this.total_pages = this.pdf_doc.numPages;
})
I have no idea if this is a good solution, but at least it worked for me.
I've had the same exact problem as you, but my solution was a bit different than the answers previously posted.
For me the problem was the fact that I was unnecessarily re-rendering with a state change. Check if you aren't re-rendering the component without properly clearing the canvas, or if you even need to re-render at all (in my case I didn't).
Hopefully this could help
In order to avoid this situation, put your canvas object in a div object as is shown below:
<div id="div_canvas">
<canvas id="cnv"></canvas>
</div>
Then, before to call pdf.js functions, remove the "div_canvas" content and recreate it:
$("#div_canvas").html("");
$("#div_canvas").html("<canvas id='cnv'></canvas>");
I had exactly the same issue when working with PDF.js, the solution to this is,
You will have to clear your context after the render completes.
if (context) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
}
This will make sure that the context is cleared and ready for the next render and the error disappears.
this worked for me.
In some cases, this error will be displayed when the pdf has action buttons such as next/previous or scaling.
In this cases, often you have a function for rendering pdf page such as:
renderPage(num) {
// Using promise to fetch the page
pdfDoc.getPage(num).then(function (page) {
const viewport = page.getViewport({scale: scale});
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
const renderContext = {
canvasContext: ctx,
viewport: viewport
};
page.render(renderContext);
});
}
To fix the error just perform following changes:
Add two variable for controlling conflict and cache waiting page number:
pageRendering = false; // Check conflict
pageNumPending = null; // Cache waiting page number
Use these variables as follow:
renderPage(num) {
if (this.pageRendering) { // Check if other page is rendering
this.pageNumPending = num; // Cache waited page number until previous page rendering completed
} else {
this.pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function (page) {
const viewport = page.getViewport({scale: scale});
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
const renderContext = {
canvasContext: ctx,
viewport: viewport
};
const renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function () {
this.pageRendering = false;
if (pageNumPending !== null) {
// Waited page must be rendered
this.renderPage(pageNumPending);
// Must be set to null to prevent infinite loop
this.pageNumPending = null;
}
});
});
One possible cause: React Strict mode renders twice

pdfjs: How to create more than one canvas to show all the pages?

I am following the approach of
here. The problem is that all the pages are in first canvas. This is because I have only one canvas and I am not sure how I can generate more canvas one after other?
function handlePages(page)
{
var viewport = page.getViewport(canvas.width / page.getViewport(1.0).width);
var ctx = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({ canvasContext: ctx, viewport: viewport });
//Add it to the web page
div.appendChild( canvas);
//Move to next page
currPage++;
if ( $scope.pdfDoc !== null && currPage <= numPages )
{
$scope.pdfDoc.getPage( currPage ).then( handlePages );
}
}
you cut out part of the code from the linked answer that you took this from. notice the document.createElement( "canvas" ). That creates a new canvas for every page.

Resources