Render raw image from response - bixby

Is there a way to render image we get from the response?
My response looks like this:
var rawResponse = "�PNG...."; // truncated for example
I saw in all examples that image is rendered through URL only, either from local assets or external URL.
When I saw that it doesn't work when I just put it into my view, I also tried converting it to base64 but still it doesn't render. This is what I used:
var base64 = require("base64");
var rawResponse = "�PNG....";
var base64Response = base64.encode(rawResponse);
return 'data:image/png;base64,'+b64Response;
Is there a way to render image not using local files or external URL?
EDIT
So here's how code looks like
var base64 = require("base64");
module.exports.function = function getImage (query) {
const result = {}
const image = http.getUrl("https://via.placeholder.com/150/f66b97");
result.image = toBase64(image);
return result;
}
const toBase64 = (img) => {
var b64Response = base64.encode(img);
let src = 'data:image/png;base64,'+b64Response;
return src;
}
structure (ImageResult) {
description (Image Result)
property (image) {
type (Image)
min (Optional) max (One)
}
}
structure (Image){
property (image) {
type (core.BaseImage)
min (Optional) max (One)
visibility (Default)
}
}
layout {
match: ImageResult (this)
mode (Details)
content {
section {
content {
divider
image {
url{
template ("#{value (this.image)}")
}
}
divider
}
}
}
}
In this code i just simplified the usage. This still works when i provide URL, local or external, or provide some image in base64 format.
Either the response is bad or the conversion is not done well... However when i try to convert it into base64 as a result i get broken image.
I'm i doing something wrong?

I've confirmed that this works. I would recommend checking the image data being returned to make sure the correct information is being encoded and returned.
Additionally, you will also need to define the image key in your result view where the url is your encoded return string.

Related

imap nodejs download link consists utf8 encoded special characters not coming out right

imap node module to parse the body of the email which consists of a download link, now the new link has been changed to UTF encoding, thus the already implemented code is screwing up the decoding of the link somehow
Is there some different kind of encoding that is happening that I might be missing
Old URL copied from email
https://www.yyyy.com/Distributor/Requests/Req_allrptslink.aspx?qrytype=U3xXQlJJQTI3Mjg2NDg4ODQ5MnwyMDIyMTAyNg==
Old URL after parsing
Click Here<https://www.yyyy.com/Distributor/Requests/Req_allrptslink.aspx?qrytype=U3xXQlJJQTI3Mjg2NDg4ODQ5MnwyMDIyMTAyNg==> to download
New URL copied from email
https://www.xxxx.com/c/?u=iuuqt%3B00ngt%2Flgjoufdi%2Fdpn0ngt0Ejtusjcvups0Sfrvftut0Sfr%60bmmsqutmjol%2Fbtqy%40rszuzqf%3EV4yYRmKKRUJ4Nkh3OUl2OkNzPYxzNEJzNUFxNx%3E%3E&p=qqttqbdb.bqeesknn--215863907-4CBE237A-EDDA-4E4B-BA14-F8CF20433D79.1.1&e=s1 (it might not be the same url as below, as i just picked it up from one of the urls, but just giving idea of the structure)
New URL parsed by the code
`<https://www.xxxx.com/c/?u=3Dundefined&p=3Dqqttqbdb.=
bqeesknn--215863899-9FB37C90-7A33-4C85-A59B-C65016E89B11.1.2&e=3Ds1=20
Dear Client,=20`
there is no ending symbol > which is very weird
code snippet :
parseBody(stream, info) {
let buffer = '';
stream.on('data', function(chunk) {
buffer += chunk.toString('utf8');
});
stream.once('end', () => { processBody(buffer) });
}
function removeCarriageReturn(body) {
return body.replace(/\r?\n|\r/g, "");
}
processBody(body) {
body = utils.removeCarriageReturn(body);
if( body.toString().includes("www.xxxx")) {
var host = "https://www.xxxx.com/c/?";
} else {
var host = "https://www.yyyyy.com/Distributor/Requests/Req_allrptslink.aspx?";
}
const linkDelimiter = '>';
let url = body.toString().split(host)[1].split(linkDelimiter)[0];
url = host + url;
.... more lines
}
parsebody is used in msg.on() under fetch emails u can read the similar sample code here https://www.npmjs.com/package/imap. Can someone give some insights on how to debug atleast thanks.

how to load atlas using base64 in phaser3?

I am making a phaser3 playable ad and require to put images and other assets in a single HTML file. I can load the images using textures.addBase64 but how can I load atlas using base64.
Also if you could tell me how to put JSON in the HTML file so that I can refer to it while loading the atlas.
Thank you 🙂
Untested personally but take a look at this solution
private loadBase64Atlas(key: string, data: string, json: object): void {
const imageElement = new Image();
imageElement.onload = () => {
this.scene.textures.addAtlas(key, imageElement, json);
this.onAssetLoaded();
};
const spriteBlob = this.base64ToBlob(data.split(',')[1], 'image/png');
imageElement.src = URL.createObjectURL(spriteBlob);
}
Adapt as needed if you're not using TypeScript. Here's the base64ToBlog implementation
The JSON object can be just bounced back and forth from and to base64 if you had the need to embed it in base64 aswell:
// get the base64 string to embed in the ad and physically store it
const atlasJSON64 = btoa(JSON.stringify(atlasJSON));
[...]
const objectatlasJSON64 = JSON.parse(atob(atlasJSON64));

How to display image files stored in mongoDB when an action is performed

I m building a form which accepts file as input (attchment) and display current attachments of a specific user.
As part of this, i am getting attachment data once my component is loaded.
base64,255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,96,0,96,0,0,255,219,0,67,0,5,4,4,4,4,3,5,4,4,4,6,5,5,6,8,13,8,8,7,7,8,16,11,12,9,13,19,16,20,19,18,16,18,18,20,23,29,25,20,22,28,22,18,18,26,35,26,28,30,31,33,33,33,20,25,36,39,36,32,38,29,32,33,32,255,219,0
Data is getting displayed in the form above.
However same data is displyed as below format in my database.
attachments
:
Binary('/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAUEBAQEAwUEBAQGBQUGCA0ICAcHCBALDAkNExAUExIQEhIUFx0ZFBYcFhISGiMaHB4f...', 0)
I am able to display data in base64 format in client console.
How can i convert in to link, when clicked the image is viewed?
Route:
app.get(
apiConfig.config.apiVersion + "/get/attachments",
bugController.getAttachmentsById
);
Controller:
let getAttachmentsById = async (req, res) => {
let tracker = await bugModel.findById(req.query.id);
await tracker.populate("attachments").execPopulate();
res.set("Content-type", "image/jpg");
let apiResponse = response.generate(false, null, 200, tracker.attachments);
res.send(apiResponse);
};
Client component:
public getAttachments() {
this.Http.getAttachments().subscribe((response) => {
this.bufferAttach =
'data:image/jpg;base64,' + response['data'][0]['attachments']['data'];
this.base64attach = this.bufferAttach.toString('base64');
console.log('ttchedDAta');
console.log(this.base64attach);
});
}
I found out that we cannot directly store images in DB, instead i have stored images in my DB using Multer and store the link in my DB. That would be more appropriate.

How to decode base64 PDF string in Flutter?

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
...

How do I validate base64 images in NodeJS/Express?

Let's say I am creating a REST API with Node/Express and data is exchanged between the client and server via JSON.
A user is filling out a registration form and one of the fields is an image input to upload a profile image. Images cannot be sent through JSON and therefore must be converted to a base64 string.
How do I validate this is indeed a base64 string of an image on the serverside? Or is it best practice not to send the profile image as a base64?
You could start by checking if the string is a base64 image, with a proper mime type.
I found this library on npm registry doing exactly that (not tested).
const isBase64 = require('is-base64');
let base64str_img = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAoHBwgHBgoIC...ljA5GC68sN8AoXT/AF7fw7//2Q==';
console.log(isBase64(base64str_img, { mime: true })); // true
Then you can verify if the mime type is allowed within your app, or make other verifications like trying to display the image file and catch possible error.
Anyway, If you want to be really sure about user input, you have to handle it by yourself in the first place. That is the best practice you should care about.
The Base64 value it is a valid image only if its decoded data has the correct MIME type, and the width and height are greater than zero. A handy way to check it all, is to install the jimp package and use it as follows:
var b64 = 'R0lGODdhAQADAPABAP////8AACwAAAAAAQADAAACAgxQADs=',
buf = Buffer.from(b64, 'base64');
require('jimp').read(buf).then(function (img) {
if (img.bitmap.width > 0 && img.bitmap.height > 0) {
console.log('Valid image');
} else {
console.log('Invalid image');
}
}).catch (function (err) {
console.log(err);
});
I wanted to do something similar, and ended up Googling it and found nothing, so I made my own base64 validator:
function isBase64(text) {
let utf8 = Buffer.from(text).toString("utf8");
return !(/[^\x00-\x7f]/.test(utf8));
}
This isn't great, because I used it for a different purpose but you may be able to build on it, here is an example using atob to prevent invalid base64 chars (they are ignored otherwise):
function isBase64(text) {
try {
let utf8 = atob(text);
return !(/[^\x00-\x7f]/.test(utf8));
} catch (_) {
return false;
}
}
Now, about how it works:
Buffer.from(text, "base64") removes all invalid base64 chars from the string, then converts the string to a buffer, toString("utf8"), converts the buffer to a string. atob does something similar, but instead of removing the invalid chars, it will throw an error when it encounters one (hence the try...catch).
!(/[^\x00-\x7f]/.test(utf8)) will return true if all the chars from the decoded string belong in the ASCII charset, otherwise it will return false. This can be altered to use a smaller charset, for example, [^\x30-\x39\x41-\x5a\x61-\x7a] will only return true if all the characters are alphanumeric.

Resources