Need to make a request to a api with a image encoded in base64, the request is a put, and i was trying making in the body section using the raw format and adding i.e. this json:
{
"picture": {
"name": "/Users/Cokeina/Desktop/imagenes/default_avatar.png",
"content_type": "image/png",
"file": "base64string"
}
}
but seems like this isn't working, what is the correct way to do this?
$image = $imagedir . 'example. jpg'; $image_file = fopen($image, 'r'); $image_data = fread($image_file, filesize($image)); header("Content-type: image/jpeg"); echo 'data:image/jpeg;base64,' . base64_encode($image_data);
Encode/Decode the variable/response using Postman itself To Base64 encode/decode, the quickest way is to use JavaScript methods btoa, atob: atob — It turns base64-encoded ASCII data back to binary. btoa — It turns binary data to base64-encoded ASCII.
You could find online base64 image encoder. They encode an image to a string.
The example of raw body in JSON format in the POSTMAN:
"profile": { "first_name": "John", "last_name": "Dow", "photo": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=" }
I think, that "name" and "content_type" is obvious in your JSON.
This is how I do it:
// JSON body in Postman
{
"first_name": "John",
"last_name": "Doe",
"photo": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABJgAAASsCAYAAADDvzILAAAZy3pUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZpZkhw5kkT/cYo5AvblOIZNpG8wx5+niCSHZBWlq7v6Z0SGyczIjMUdDlPTBXB3/vsf1/0X/2rx2eXSeh21ev7lkUc0fun+88/ez+Dz+/n+jf7+0t8/Pe9sfb0QeSrxmD4v9Pp5DN+e//rAt8dg/FZ+OFBfXy/Mn18Yn8P72H85..."
}
Then on the server, I store the image like so:
app.use(express.json({ limit: '50mb' })); // To allow for larger payloads
app.post("/selfie", (req, res) => {
console.log('req.body:', req.body);
var base64Data = req.body.photo.replace(/^data:image\/png;base64,/, "");
require("fs").writeFile("out.png", base64Data, 'base64', function (err) {
console.log(err);
});
res.end();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With