I would like to get the base64 code of a gif image from the internet.
The base64 should be generated from the first frame of the gif image.
I'm able to store the first frame of a gif image with the following code in nodejs:
var gifFrames = require('gif-frames');
var fs = require('fs');
gifFrames({ url: 'https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif', frames: 0 }).then(function (frameData) {
frameData[0].getImage().pipe(fs.createWriteStream('firstframe.jpg'));
});
I now need the base64 code of this stored jpg image.
Ideally the image will not be stored on the disk and just prints the base64 code.
Thanks in advance!
Since getImage() returns a ContentStream, you just need to read the Buffer and convert it to Base64. Somehow like this:
var gifFrames = require('gif-frames');
var fs = require('fs');
gifFrames({
url: 'https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif',
frames: 0
}).then(function (frameData) {
var stream = frameData[0].getImage(),
b64 = stream.read().toString('base64');
console.log(b64);
});
Related
I want to generate a pdf with images and text, for this I'm using the jsPdf package which includes this method to add images.
addImage(imageData, format, x, y, width, height, alias, compression, rotation)
The imageData argument accepts base64 format data and this part is which I'm struggling with.
My images are not local but hosted in cloudinary and I would prefer not to download them, searching on the web I've found that if I don't want to download the image I will need:
Fetch the image data, for this I'm using node-fetch package(fetch in the code).
Convert the image data into a Buffer.
Finally encode that buffer into a base64.
This is my attempt so far:
const fetchImage = async () => {
const imageUrl = <url-of-my-image>;
const response = await fetch(imageUrl, {
compress: false
});
const dataUrlPrefix = `data:${response.headers.get('content-type')};base64,`;
const body = await response.text();
const buffer = Buffer.from(body)
const imageBase64 = buffer.toString('base64');
const imageDataUrl = dataUrlPrefix+imageBase64;
doc.text("Hello world!", 10, 10);
doc.addImage(imageDataUrl, 'webp', 15, 40, 120, 120)
doc.save("a4.pdf");
}
The code runs without errors but the image is not being inserted into the pdf, it just display the "Hello World!" text but nothing else.
My guess is that I'm doing something wrong in the converting/encoding process (before I add it to jsPdf) because if I convert my image with an online converter like this one the base64 string that results is successfully decoded into an actual image when using a online base64 decoder like this one, whereas when I run the base64 output from my nodejs code i.e. the output for the imageBase64 or imageDataUrl variables in the same base64 decoder it results in not image being decoded.
I have a variable in my NodeJS application which contains base64 string of an image. I need to send a form to some server with POST request containing this image. The problem is I can't convert base64 string to an image without writing it to a filesystem. Here's my code:
const imagePath = path.resolve(__dirname, '../../../images/anomalies/' + Date.now() + '.png')
fs.writeFileSync(imagePath, img, { encoding: 'base64' })
setTimeout(() => {
fs.unlinkSync(imagePath)
}, 30_000)
const form = new FormData()
form.append('photo', fs.createReadStream(imagePath))
As you can see, I need to write base64 string to a file and then grab it with fs.createReadStream. Otherwise file won't upload. I tried converting it to ReadStream via stream-buffers (but server still not accepted that data) and also I tried to make a Blob from it but Node don't have blobs and all these modules on npm are either too old or don't have typings which is not great at all. I also tried Buffer.from(base64, 'base64'), which doesn't work as well.
Is there any way to create an uplodable image file from base64 encoded string without accessing filesystem in NodeJS?
You should be able to convert the Buffer object returned by fs.readFileSync to a base64 string
const base64Image = fs.readFileSync(imagePath).toString('base64')
I know there is a package called dart:convert which let me decode base64 image. But apparently, it doesn't work with pdf files. How can I decode the base64 PDF file in Flutter?
I want to store it in Firebase Storage (I know how to do it) but I need the File variable to do it.
I have a web service written in node js where I have a POST route. There, I create a pdf file and encode it to base 64. The response is a base64 string, look at the code.
router.post('/pdf', (req, res, next) => {
//res.send('PDF');
const fname = req.body.fname;
const lname = req.body.lname;
var documentDefinition = {
content: [ write your pdf with pdfMake.org ],
styles: { write your style };
const pdfDoc = pdfMake.createPdf(documentDefinition);
pdfDoc.getBase64((data) => {
res.send({ "base64": data });
});
});
As you can see, it returns the pdf as a base64 string.
Now, in Flutter, I have written this:
http.post("https://mypostaddreess.com",body: json.encode({"data1":"data"}))
.then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
var data = json.decode(response.body);
var pdf = base64.decode(data["base64"]);
});
}
I have the PDF in the variable 'pdf' as you see. But I don't know how to decode it to download the pdf or show it in my Flutter app.
#SwiftingDuster
a little added, maybe besides decoding, it's also necessary to create a pdf file and open it.
createPdf() async {
var bytes = base64Decode(widget.base64String.replaceAll('\n', ''));
final output = await getTemporaryDirectory();
final file = File("${output.path}/example.pdf");
await file.writeAsBytes(bytes.buffer.asUint8List());
print("${output.path}/example.pdf");
await OpenFile.open("${output.path}/example.pdf");
setState(() {});
}
library needed:
1. open_file
2. path_provider
3. pdf
I think it's better to get the BufferArray and convert it into a pdf file.
Check out my answer from here : Get pdf from blob data
This should convert base64 encoded pdf data into a byte array.
import 'packages:dart/convert.dart';
List<int> pdfDataBytes = base64.decode(pdfBase64)
.map((number) => int.parse(number));
The pdf and the image plugins seems to suit your needs for displaying pdf.
The code should be roughly like so:
import 'package:pdf/pdf.dart';
import 'package:image/image.dart';
...
Image img = decodeImage(pdfDataBytes);
PdfImage image = PdfImage(
pdf,
image: img.data.buffer.asUint8List(),
width: img.width,
height: img.height);
// Display it somehow
...
I am receiving a base64 encoded image from the client (as a screenshot) and would like to upload it to another server using multipart encoding
var base64Encoded="iVBORw0KGgoAAAANSUhEUgAAAAoAAABkCAYAAAC/zKGXAAAAK0lEQVR42u3KMQ0AAAgDsOFfJwcusMBL0t6tSToHJYqiKIqiKIqiKIri57hqIbTd/KhOmQAAAABJRU5ErkJggg==";
const x =Axios({url:"https://slack.com/api/files.upload",method:"POST", data:{title:"Hello", file: <INSERT HERE>, filetype:"png", channel: "testchannel"},headers:{Authorization: authorization,'Content-Type': 'multipart/form-data'}});
I've tried a lot here
Converting it to a buffer
var buffer = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAoAAABkCAYAAAC/zKGXAAAAK0lEQVR42u3KMQ0AAAgDsOFfJwcusMBL0t6tSToHJYqiKIqiKIqiKIri57hqIbTd/KhOmQAAAABJRU5ErkJggg==", 'base64');
Converting the buffer into a readable stream
var buffer = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAoAAABkCAYAAAC/zKGXAAAAK0lEQVR42u3KMQ0AAAgDsOFfJwcusMBL0t6tSToHJYqiKIqiKIqiKIri57hqIbTd/KhOmQAAAABJRU5ErkJggg==", 'base64');
console.log(buffer);
const readable = new Readable();
readable._read = function(){};
readable.push(buffer)
readable.push(null)
None of these seem to work. Slack API simply gives me a invalid form data response
It works if i upload via postman
PS: I have to send axios request using the nodejs server, not browser
I am receiving string base64 encoded, when I try to decode and save in to an image file, it seems to be everything working fine, but when I download open the file, my viewer does not recognize it.
I know my string is a valid image because I use http://www.freeformatter.com/base64-encoder.html
and it sends me the right image.
Is there something I am missing?
var imagestring = "/9j/2wCEAA0JCQsJCA0LCgsODQ0PEx8UExEREyYbHRcfLSgwLy0oLCsyOEg9MjVENissP1U/REpNUFFQMDxYX1hOXkhPUE0BDQ4OExATJRQUJU00LDRNTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTf/AABEIAHgAoAMBIQACEQEDEQH/3QAEAAr/xAGiAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgsQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+gEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoLEQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4Q=hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDzcU6gBamtztlVj0BzTA2rK5njm3xHaCMdamuN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Wb3AqYAORSUAFIaYCUUwEpKYBRTA//X8xooAkQY579qepOeRTQh/lq3I+U0vlNjjB+hp2C5XO4mgRsfQVFxk6KEGBTs1ABmkpgFJQAUlUAlFMBKWgD/0PMaXtQA4NgU8HPamBI=opxUihgeRxVElXvTxWJQ6lpAFFMBKKAEoqgCkpgFFAH/0fMhS4zQA5Bg89KsrFVJXEyVI8U8lY1LN0Fa2sSZobJzUi1yssdS0AFFABRTQBSUwCimAUlAH//S8xHWpAD6UALkVaicGMEnpxVR3ExXuAmODzURD3b7UWRyOdqDNOcugkQlAhwev1pVPNZFD6WkAUUAFFMAopgFJTAKKAP/0/MgcUu8kYzQAnSpI5CnB6UICdgJE4AJ6iozdzmEwCVliJyY1OFJ9SB1NE1cRFThUjHA04UgCloAKKoAopgFFABRQB//1PNNnHPFIv3hkcUAObaBxTaAJoG8sknOKY4yxI4BND2ENxTqkYopc0AOzRQAUUwClpgFFABRQB//1fNnBAzTBuHQUkA7BI5HIpQCDkDFCAX5j2pdrelAFmx0y51CUx26AsBnk4qOW0kgcpIMMpwajmV7CIzGR2pNp9KoYoU+lLtPpQAu0+lG0+lMA2n0pdp9KYBtPpRtPpQAbT6UFTQB/9k=";
var decodedImage = new Buffer(imagestring, 'base64');
fs.writeFile('imagedecoded.jpg', decodedImage , function(err) {});