I will like to save an image from a web URL to the device can anyone help?
I've tried using the imageSource module but it only speaks of images from local device
const imageSourceModule = require("tns-core-modules/image-source");
const fileSystemModule = require("tns-core-modules/file-system");
imageSourceModule.fromUrl(webURL).then((res) => {
const folderDest = fileSystemModule.knownFolders.currentApp();
const pathDest = fileSystemModule.path.join(folderDest.path, "test.png");
const saved = res.saveToFile(pathDest, "png");
if (saved) {
console.log("Image saved successfully!");
this.image = imageSourceModule.fromFile(pathDest);
}
thanks to #Narendra Mongiya for the first answer which help get the image from url
This is what your code should be (I am assuming that your webURL returns jpg/png etc)
const imageSource = require('image-source');
imageSource.fromUrl(webURL).then((res: any) => {
this.imageUrl = res;
}).catch(err => {
this.imageUrl = this.getIconSource('default_image');
});
and in html file
<Image [src]="imageUrl" loadMode="async"></Image>
and for the default images if URL return blank
public getIconSource(icon: string): string {
return isAndroid ? `res://${icon}` : 'res://images/' + icon;
}
Related
The image is uploaded to firebase and returned as a data_URL that looks like this:
https://firebasestorage.googleapis.com/v0/b/app_name/o/posts%2postId?alt=media&token=token
I am trying to check if the file type is a video or an image, then return a div depending on the "mediaType". Because firebase storage doesn't include the file extension in the url, it is difficult to determine the file type.
First attempt:
const [mediaType, setMediaType] = useState(null);
useEffect(() => {
if (postImage) {
const storageRef = firebase.storage().ref();
storageRef.child(postImage).getDownloadURL().then(url => {
fetch(url)
.then(res => res.blob())
.then(blob => {
let type = blob.type;
if (type.startsWith("image")) {
setMediaType("image");
} else if (type.startsWith("video")) {
setMediaType("video");
} else {
setMediaType("other");
console.log("Unknown file format: " + type);
}
});
});
}
}, [postImage]);
Second attempt:
const handleFile = async (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = async (e) => {
const dataURL = e.target.result;
if (dataURL.startsWith('data:image/')) {
setMediaType('image');
setDataUrl(dataURL);
console.log("Image: " + dataURL);
} else if (dataURL.startsWith('data:video/')) {
setMediaType('video');
setDataUrl(dataURL);
console.log("Video: " + dataURL);
} else {
let response = await fetch(dataURL);
let type = response.headers.get("Content-Type");
if (type.startsWith("image")) {
setMediaType("image");
setDataUrl(dataURL);
} else if (type.startsWith("video")) {
setMediaType("video");
setDataUrl(dataURL);
} else {
setMediaType("other");
console.log("Unknown file format: " + type);
}
}
}
reader.readAsDataURL(file);
}
The div inside my return statement:
<div className="w-full px-3">
{mediaType === 'image' ? <img className="shadow-md w-full" src={postImage || 'default-image.jpg'} alt="" /> : null}
{mediaType === 'video' ? <ReactPlayer layout="fill" url={postImage} config={{file:{attributes:{controlsList:'nodownload'}}}} controls onContextMenu={e => e.preventDefault()}/> : null}
{mediaType === 'other' ? <p>File is not an image or video</p> : null}
</div>
What I would do is add metadata while uploading the file to firebase. You can check the documentation to see how:
//This is a metadata, you can customize these
//as you can see the content type is set to be image/jpeg
var newMetadata = {
cacheControl: 'public,max-age=300',
contentType: 'image/jpeg'
.........
.........
};
You will use this metadata while uploading the file using:
storageRef.updateMetadata(newMetadata).......
And when reading the file read out the metadata that you set to the file to for example detect its type:
storageRef.getMetadata().then((metadata) => {
//use this metadata to know the type here.......
})
Hope this gives you an idea of what to do.
I'm trying to get an image (served to the client from an express server) to display. I've received the data from the server and have parsed this from binary, to blob, to datauri. I, however, am still getting a broken image on my page.
Below is my code:
const [imageUrl, setImageUrl] = useState('');
const [profilePic, setProfilePic] = useState('');
const [errors, setErrors] = useState('');
const binaryToBase64 = () => {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = base64Data.toString("base64");
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
useEffect(() => {
// Get all customer media
let tempPhoto = '';
await actions.getMediaReference(customerId)
.then(resp => {
// Set profile pic via reference from DB
tempPhoto = resp.data.find(({ isprofile }) => isprofile);
})
.catch(err => errors.push(err));
await actions.getMediaSource(tempPhoto.key)
.then(resp => {
// console.log("specific data: ", typeof resp.data); // Not sure of the format: ����
const blob = binaryToBase64(resp.request.response, "image/jpg"); // convert to base 64 - I assume I'm getting binary code
const url = URL.createObjectURL(blob);
console.log('blob: ', blob); // prints this which also isn't accepted: blob:http://localhost:3000/1231233234
console.log('url: ', url);
// setImageUrl(url)
// My thinking is that it needed to be further processed (got this from another stackoverflow page)
fileToDataUri(blob)
.then(dataUri => {
setImageUrl(dataUri)
})
setProfilePic({ ...profilePic, image : resp.data });
})
.catch(err => errors.push(err));
}
return(
<>
<img src={imageUrl} />
</>
)
Trying this api out via Postman works - I get the image after a very tiny delay. I can't say that I see the error here but I've tried a few things. After running the base64 code in a converter I can see that something isn't translating correctly. I feel like this shouldn't be that complicated and that I've over-complicated the solution so any help/advice would be much appreciated!
Thanks
I create a PDF in ReactJS using react-pdf/renderer and download it using file-saver.
Here is my code that creates the PDF and downloads it:
const LazyDownloadPDFButton = (number, date, totalHours, formattedHours) => (
<Button
className={classes.download}
onClick={
async () => {
const doc = <InvoicePDF number={number} date={date} totalHours={totalHours} formattedHours={formattedHours} />
const asPdf = pdf()
asPdf.updateContainer(doc)
const blob = await asPdf.toBlob()
saveAs(blob, `PDF${number}.pdf`)
}}>
Download
</Button>
)
where InvoicePDF is a separate component that renders the PDF pages with the necessary arguments, as in react-pdf/renderer documentation page.
Before download the actual PDF I have to merge it with another existing PDF that will be choose from computer drive. To do that I have the next code snippet:
fileRef = useRef()
<Button onClick={() => fileRef.current.click()}>
Upload file
<input
ref={fileRef}
type='file'
style={{ display: 'none' }}
/>
</Button>
Which returns me the details of the file.
I tried to updateContainer with this selected file, but there are errors.
How this new file should be merged with the InvoicePDF that is created?
In the meantime, I tried to create my last blob from arrayBuffers like this:
This is the function that concatenates the created PDF with the selected PDF and it returns the correct sum.
function concatArrayBuffers(buffer1, buffer2) {
if (!buffer1) {
return buffer2;
} else if (!buffer2) {
return buffer1;
}
var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp.buffer;
};
And my method now have a finalBlob that is created with arrayBuffers but the problem is that the resulted PDF will always contain just the content of the second arrayBuffer (which is either the selected pdf or the created pdf)
const LazyDownloadPDFButton = (number, date, totalHours, formattedHours) => (
<Button
className={classes.download}
onClick={
async () => {
const doc = <InvoicePDF number={number} date={date} totalHours={totalHours} formattedHours={formattedHours} />
const asPdf = pdf()
asPdf.updateContainer(doc)
const initialBlob = await new Blob([fileRef.current.files[0]], { type: 'application/pdf' }).arrayBuffer()
const blob = await (await asPdf.toBlob()).arrayBuffer()
const finalArrayBuffer = concatArrayBuffers(initialBlob, blob)
const finalBlob = new Blob([finalArrayBuffer], { type: 'application/pdf' })
saveAs(finalBlob, `PDF${number}.pdf`)
}}
>
Download
</Button>
)
Just A Simple Solution Made By me...
https://github.com/ManasMadan/pdf-actions
https://www.npmjs.com/package/pdf-actions
import { createPDF,pdfArrayToBlob, mergePDF } from "pdf-actions";
// Async Function To Merge PDF Files Uploaded Using The Input Tag in HTML
const mergePDFHandler = async (files) => {
// Converting File Object Array To PDF Document Array
files.forEach((file)=>await createPDF.PDFDocumentFromFile(file))
// Merging The PDF Files to A PDFDocument
const mergedPDFDocument = await mergePDF(files)
// Converting The Merged Document to Unit8Array
const mergedPdfFile = await mergedPDFDocument.save();
// Saving The File To Disk
const pdfBlob = pdfArrayToBlob(mergedPdfFile);
};
Solution
After some research and a lot of failed tries I came to an answer on how to merge the PDFs in the correct order, and bonus add an image (in my case a signature) on every page of the final PDF.
This is the final code:
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
async function mergeBetweenPDF(pdfFileList, number) {
const doc = await PDFDocument.create()
const getUserSignature = () => {
switch (selectedUser.id) {
case 1:
return FirstImage
case 2:
return SecondImage
default:
return null
}
}
const pngURL = getUserSignature()
const pngImageBytes = pngURL ? await fetch(pngURL).then((res) => res.arrayBuffer()) : null
const pngImage = pngURL ? await doc.embedPng(pngImageBytes) : null
const pngDims = pngURL ? pngImage.scale(0.5) : null
const initialPDF = await PDFDocument.load(pdfFileList[0])
const appendixPDF = await PDFDocument.load(pdfFileList[1])
const initialPDFPages = await doc.copyPages(initialPDF, initialPDF.getPageIndices())
for (const page of initialPDFPages) {
if (pngURL) {
page.drawImage(pngImage, {
x: page.getWidth() / 2 - pngDims.width / 2 + 75,
y: page.getHeight() / 2 - pngDims.height,
width: pngDims.width,
height: pngDims.height,
});
}
doc.addPage(page)
}
const appendixPDFPages = await doc.copyPages(appendixPDF, appendixPDF.getPageIndices())
for (const page of appendixPDFPages) {
if (pngURL) {
page.drawImage(pngImage, {
x: page.getWidth() / 2 - pngDims.width / 2 + 75,
y: page.getHeight() / 2 - pngDims.height,
width: pngDims.width,
height: pngDims.height,
});
}
doc.addPage(page)
}
const base64 = await doc.saveAsBase64()
const bufferArray = base64toBlob(base64, 'application/pdf')
const blob = new Blob([bufferArray], { type: 'application/pdf' })
saveAs(blob, `Appendix${number}.pdf`)
}
const LazyDownloadPDFButton = (number, date, totalHours, formattedHours) => (
<Button
className={classes.download}
onClick={
async () => {
const doc = <InvoicePDF number={number} date={date} totalHours={totalHours} formattedHours={formattedHours} />
const asPdf = pdf()
asPdf.updateContainer(doc)
let initialBlob = await new Blob([fileRef.current.files[0]], { type: 'application/pdf' }).arrayBuffer()
let appendixBlob = await (await asPdf.toBlob()).arrayBuffer()
mergeBetweenPDF([initialBlob, appendixBlob], number)
}}
>
Download
</Button>
)
So the LazyDownloadPDFButton is my button that request the respective parameters to create the final PDF. InvoicePDF is my created PDF with the parameters, and initialBlob is the PDF that I upload on my page, which requires to be the first in merged PDF, and appendixBlob is the created PDF that will be attached to initialBlob.
In mergeBetweenPDF I am using pdf-lib library to create the final document, where I create the image, take the 2 initial PDFs that are send, looping them, add the image on every page, and then add every page to the final doc which will be downloaded.
Hope one day this will help someone.
I have a zip file containing some images, mp4s and a text file. The text file i am reading like so:
jszip
.loadAsync(arrayBuffer)
.then(({ files }) => {
const txtFiles = Object.entries(files).filter(([fileName]) =>
fileName.endsWith('.txt'),
);
if (!txtFiles.length) {
throw new Error('No txt files found in archive');
}
return txtFiles
.sort(([a], [b]) => a.length - b.length)[0][1]
.async('string');
})
and it works fine. But I need to get all the images/mp4s in the file as well, so I tried:
jszip
.loadAsync(arrayBuffer)
.then(({ files }) => {
const jpgs = [];
const mediaFiles = Object.entries(files).filter(([fileName]) =>
fileName.endsWith('.jpg'),
);
if (!mediaFiles.length) {
throw new Error('No media files found in archive');
}
mediaFiles.forEach(i => {
blob = new Blob([i], {
type: 'image/jpeg',
});
img = new Image();
img.src = URL.createObjectURL(blob);
jpgs.push(img);
});
return jpgs;
})
now when i try to render the jpgs array, i get a bunch of img elements like so:
<img alt="img" src="blob:http://localhost:3000/d64b16c7-aa9c-49a7-96cc-ed4eafc6a054">
but no images / broken image icons. What I am doing wrong?
Apparently I wasn't using the blob correctly, the following code solved it for me, with thanks to Loris Bettazza:
mediaFiles.forEach(([, image]) => {
image.async('blob').then(blob => {
const img = new Image();
img.src = URL.createObjectURL(blob);
document.body.prepend(img);
});
});
I have a problem with displaying image on my project. I want in the .subscribe task the download url to equal as image. So it can display it. But when I do that it shows an error message:
Type 'UploadTaskSnapshot' is not assignable to type 'string'.
Here is the code:
export class PostDashboardComponent implements OnInit {
title: string;
image: string = null;
content: string;
buttonText: string = "Create Post";
uploadPercent: Observable<number>;
downloadURL: Observable<string>;
constructor(
private auth: AuthService,
private postService: PostService,
private storage: AngularFireStorage
) { }
ngOnInit() {
}
uploadImage(event) {
const file = event.target.files[0]
const path = `posts/${file.name}`
const fileRef = this.storage.ref(path);
if (file.type.split('/')[0] !== 'image') {
return alert('only image files')
} else {
const task = this.storage.upload(path, file)
this.uploadPercent = task.percentageChanges();
task.snapshotChanges().pipe(
finalize(() => this.downloadURL = fileRef.getDownloadURL() )
)
.subscribe(url => (this.image = url))
console.log('Image Uploaded!');
What should I change to make it work because I am an amateur. Thank you for your help.
I found the answer and is this:
uploadImage(event) {
const file = event.target.files[0]
const path = `posts/${file.name}`
const fileRef = this.storage.ref(path);
if (file.type.split('/')[0] !== 'image') {
return alert('only image files')
} else {
const task = this.storage.upload(path, file);
const ref = this.storage.ref(path);
this.uploadPercent = task.percentageChanges();
console.log('Image uploaded!');
task.snapshotChanges().pipe(
finalize(() => {
this.downloadURL = ref.getDownloadURL()
this.downloadURL.subscribe(url => (this.image = url));
})
)
.subscribe();