How to convert blob to png or jpg? - javascript

I have used react-images-zoom-print https://www.npmjs.com/package/react-images-zoom-print I am taking a photo of the API with a blob like this:
const downloadDepositMoneyInfosClickHandler = (row) => {
props.service(row.id, (status, data) => {
var blob = new Blob([data], { type: "image/png" });
var objectUrl = URL.createObjectURL(blob);
imageRef.current = objectUrl;
setImgDialogOpen(true);
});
};
> console.log(imageRef.current)==>
blob:http://localhost:3000/c85aiua36d-2fua-43a8-a881-311d287ed37e
and in Lightbox:
<Lightbox
images={[{src:"'"+imageRef.current+"'"}]}
isOpen={imgDialogOpen}
onClose={closeImgDialog}
rotatable={true}
zoomable={true}
onPrint={() => window.print()}
/>
But it does not show it, I think it should become a png or jpg.
I want to turn it into a photo with the type png or jpg.
How should I convert it?

Try this one:
const blobToImage = (blob) => {
return new Promise(resolve => {
const url = URL.createObjectURL(blob)
let img = new Image()
img.onload = () => {
URL.revokeObjectURL(url)
resolve(img)
}
img.src = url
})
}

Related

How to add custom metadata in PDF file using react js?

I'm taking input as a PDF file and using javascript to add custom metadata, but I'm not getting a satisfactory result.
Below is a sample method code that I used to add custom metadata that is first converted to blob type and then added, but when we convert its blob data to base64 and download the file and check the properties, we cannot find it.
const blobToBase64 = (blob: any) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
const updatePDFMetaData = (file: any, metadata: any) => {
let convertBlobToBase64: any;
const selectedFile = file;
const reader = new FileReader();
reader.readAsArrayBuffer(selectedFile);
reader.onload = async (event:any) => {
const fileBuffer: any = event?.target?.result;
const blob: any = new Blob([fileBuffer], { type: selectedFile.type });
Object.keys(metadata).forEach((key: any) => {
blob[key] = metadata[key];
});
convertBlobToBase64 = await blobToBase64(blob);
console.log("convertBlobToBase64", convertBlobToBase64);
};
};

converting image to base64 - image becomes invisible

I'm trying encode an image to base64, (so I can later send it this way to a backend server). Everything seems to work until I use JSON.stringify() on the object that has the encoded image in it.
I think It gets lost in the JSON.stringify() and I can't seem to find a solution. I've been working for weeks on this issue and I couldn't find an answer anywhere. Please help!
const [baseImage, setBaseImage] = useState('');
const [baseImageCorrect, setBaseImageCorrect] = useState('');
const convertBase64 = (file) => {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = () => {
resolve(fileReader.result);
};
fileReader.onerror = (error) => {
reject(error);
console.log(error);
};
});
};
const uploadImage = async (e) => {
const file = e.target.files[0];
const base64 = await convertBase64(file);
const base64RemovedType = base64.split(',')[1];
setBaseImage(`${base64RemovedType}`);
};
useEffect(() => {
setBaseImageCorrect(baseImage);
console.log('current:' + baseImageCorrect);
//prints out a long string with the RIGHT information
}, [baseImage, baseImageCorrect]);
const EncodedImage = JSON.stringify({
fileBase64: (baseImageCorrect, { encoding: 'base64' }),
});
console.log(EncodedImage)
//PRINTS THIS: "fileBase64":{"encoding":"base64"}} , without the encoded image string
I am assuming u need the key baseImageCorrect and encoding key at the same level.
Use this instead:
const EncodedImage = JSON.stringify({
fileBase64: {baseImageCorrect, encoding: 'base64' },
});

How can I get video bitrate with javascript

I want to get the bitrate of video that uploader, because the backend need it.
var video = document.createElement('video');
video.preload = 'metadata';
video.src = URL.createObjectURL(document.getElementById('fileUp').files[0]);
window.URL.revokeObjectURL(video.src);
console.log(video.bitrate);
You can get the video duration then simply divide the file size by it to get an approximation (subtitles, audio and metadata would also be included in this value), as far as i know there is no standard api for getting the bitrate directly.
Example (credits https://stackoverflow.com/a/67899188/6072029 ) :
<div>
<script>
const getVideoInfos = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const media = new Audio(reader.result);
media.onloadedmetadata = () => resolve({
duration: media.duration,
file_size: file.size,
bitrate: file.size / media.duration,
});
};
reader.readAsDataURL(file);
reader.onerror = (error) => reject(error);
});
const handleChange = async (e) => {
const infos = await getVideoInfos(e.target.files[0]);
document.querySelector("#infos").innerText = `Infos : ${JSON.stringify(infos, null, 4)}`;
};
</script>
<input type="file" onchange="handleChange(event)" />
<p id="infos">infos: </p>
</div>

How can I read the data in the excel file with reactjs or javascript using the path to the file

I want to read the contents of the file directly by using the file path. I can do this by having the file selected. But I don't know how to do it using the direct file path. I could not find any examples or sources for this. Below is how I read the file by selecting it from the input.
import * as XLSX from 'xlsx';
var items = [];
readExcel = (file) => {
const promise = new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
fileReader.onload = (e) => {
const bufferArray = e.target.result;
const wb = XLSX.read(bufferArray, { type: "buffer" });
const wsname = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
const data = XLSX.utils.sheet_to_json(ws);
resolve(data);
};
fileReader.onerror = (error) => {
reject(error);
};
});
promise.then((d) => {
this.items = d;
console.log(this.items)
// fill dictionary
this.dictionary = Object.assign({}, ...this.items.map((x) => ({ [x.PartNumber]: x.Cost })));
console.log(this.dictionary)
});
};
<input
type="file"
onChange={(e) => {
const file = e.target.files[0];
this.readExcel(file);
}}
/>
I beleive it should work:
const req = new XMLHttpRequest();
req.responseType = "arraybuffer";
req.open("GET", "https://.../MyExcelFile.xlsx", true);
req.onload = () => {
const bufferArray = req.response;
const wb = XLSX.read(bufferArray, { type: "buffer" });
...
I couldn't find a direct read operation. I converted the excel file to json format and got my job done.

Js Convert Photo Cam in Input File

I have a webcam that is taking a photo, mediaDevices.getUserMedia, in local SrcObject, but I want the photo to go to an input type = file. how do i convert?
You can't just programmatically put File object to <input type="file">
What you can do is create a Blob object out of captured screenshot and later on send it with rest of formdata.
const getScreenshotFromCameraBlob = () => {
const canvas = document.createElement('canvas');
const video = document.createElement('video');
video.setAttribute("autoplay", true);
return new Promise((resolve, reject) => navigator.mediaDevices
.getUserMedia({
video: true
})
.then((stream) => {
video.srcObject = stream;
video.addEventListener("loadeddata", () => {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.toBlob(resolve, 'image/jpeg');
})
})
.catch(reject)
)
}
getScreenshotFromCameraBlob()
.then(blob => {
console.log(blob);
sendScreenshot(blob);
})
.catch(error => {
console.log(error)
})
const sendScreenshot = (blob) => {
const formData = new FormData();
formData.append("screenshot", blob);
fetch('', {
method: 'POST',
body: formData
})
}

Categories

Resources