Render blob image with Angular 4 - html

I'm trying to render an user image that comes from soap server response, it not should be difficult but i dont know how start to do.
This is the code of the request way:
this.http.post(wsurl, xml, {withCredentials: true, headers: headers})
.toPromise()
.then((response) =>....
This is the response:
------=_Part_18_19650293.1510067330953
Content-Type: text/xml; charset=UTF-8
Content-Transfer-Encoding: binary
Content-Id: <94A7DA36FAAE3F537AD3295BF2DFF5AD>
<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body>
..... data of the user
</soapenv:Body></soapenv:Envelope>
------=_Part_18_19650293.1510067330953
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
Content-Id: <ACC047E73E810E9A61470902A1E4483F>
����JFIFdd��C��C��dd��
��6!aR�1AQ�"#q�2�4CSb���������?����9#�P3��9#�P3��9#�P3�s�P3�P3�P3�P3�P3�P3�P3�P3�P3�P3�P3�P3�PC�=�5w�
C��P�x#�=�j8�^��N����]X����4��3fql�]�Ʈ��VG-5m+^�:w���S�+���A���c�8����Yd�9`�t��g8��&W�� صw�
C��P�x#�=�5w��8#��S�
NT���L&��5CY�O�d��:�"ۋ{��z�om�A��I&��� ��$����襉��J�Z湦��75�?��^�#kb�H?-#Zʆ�����x��>�D��� jp���Z������;��j�(8��]����&��WO$������%�'����Z
��*&�ꞟ� O5�1��%�D������;��j�(������r���g(�-��m-e]+&mK)��6T0��Z�=��F##A��8ÍUP�cC��Ml���9sJ��P3��9A8�8�8��s\�5�������q�T����ps]N���p��X��DZ�p�������M8�)VC�
;cO���?�����9#�9#�9#�9AP�x#�=�5w�
C���3 ����ĩ ғ3|��F�!�:��[_��*�-Ѹ]�P��0ʌB(���ߍ�{�7�ͽ����ר{� j���������� jp���
3�h�]ӵ2�M�;�
qh1��!��S`���M�i>��ϧ�r�3! X=�����S5��5�
kE�Ѱ �S�
N58#��-A�~�����|媆�,����{��I��������Sbs�m�F����o��S��'��z��Ӵ�&�F��os���A�##Ac`*���l]����2��k؇X?{nH?����*�Y31hc�.I�����2ٚ���k���n(=��;��<���W�!���̓~�3XF��?؁���\)�����䩫���)��q���=�A�;�ªSE9������=�=���z�,r���t_�i���no���9!�g(1�QSA5D�ӧc�%��V��YW5uT�u�4�.y������ ����������7Ӹ���Z�`�"���o��?����^Y�(0���8��>^k���b����d��
------=_Part_18_19650293.1510067330953--
Then I cut the image data to :
����JFIFdd��C��C��dd��
��6!aR�1AQ�"#q�2�4CSb���������?����9#�P3��9#�P3��9#�P3�s�P3�P3�P3�P3�P3�P3�P3�P3�P3�P3�P3�P3�PC�=�5w�
C��P�x#�=�j8�^��N����]X����4��3fql�]�Ʈ��VG-5m+^�:w���S�+���A���c�8����Yd�9`�t��g8��&W�� صw�
C��P�x#�=�5w��8#��S�
NT���L&��5CY�O�d��:�"ۋ{��z�om�A��I&��� ��$����襉��J�Z湦��75�?��^�#kb�H?-#Zʆ�����x��>�D��� jp���Z������;��j�(8��]����&��WO$������%�'����Z
��*&�ꞟ� O5�1��%�D������;��j�(������r���g(�-��m-e]+&mK)��6T0��Z�=��F##A��8ÍUP�cC��Ml���9sJ��P3��9A8�8�8��s\�5�������q�T����ps]N���p��X��DZ�p�������M8�)VC�
;cO���?�����9#�9#�9#�9AP�x#�=�5w�
C���3 ����ĩ ғ3|��F�!�:��[_��*�-Ѹ]�P��0ʌB(���ߍ�{�7�ͽ����ר{� j���������� jp���
3�h�]ӵ2�M�;�
qh1��!��S`���M�i>��ϧ�r�3! X=�����S5��5�
kE�Ѱ �S�
N58#��-A�~�����|媆�,����{��I��������Sbs�m�F����o��S��'��z��Ӵ�&�F��os���A�##Ac`*���l]����2��k؇X?{nH?����*�Y31hc�.I�����2ٚ���k���n(=��;��<���W�!���̓~�3XF��?؁���\)�����䩫���)��q���=�A�;�ªSE9������=�=���z�,r���t_�i���no���9!�g(1�QSA5D�ӧc�%��V��YW5uT�u�4�.y������ ����������7Ӹ���Z�`�"���o��?����^Y�(0���8��>^k���b����d��
EDIT1
These methods are the methods that I have used to convert binary to base64
let b64 = this._arrayBufferToBase64(result)
this.imgStr = 'data:image/jpeg;base64,' + b64
_arrayBufferToBase64( buffer ) {
let binary = '';
let bytes = new Uint8Array( this.str2ab(buffer) );
let len = bytes.byteLength;
console.log("lenbytes " + len)
for (let i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}
str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
The methods generate a src to the image like this:
data:image/jpeg;base64,/f/9//3//f8AABAASgBGAEkARgAAAAEAAgAAAAAAZAAAAGQAAAAAAP3//f8AAEMAAAABAAEAAQABAAEAAQABAAEAAQABAAIAAQABAAEAAgACAAIAAQABAAIAAgACAAIAAgACAAIAAgACAAMAAgADAAMAAwADAAIAAwADAAQABAAEAAQABAADAAUABQAFAAUABQAFAAcABwAHAAcABwAIAAgACAAIAAgACAAIAAgACAAIAP3//f8AAEMAAQABAAEAAQACAAIAAgAFAAMAAwAFAAcABQAEAAUABwAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAP3//f8AABEACAAAAGQAAABkAAMAAQARAAAAAgARAAEAAwARAAEA/f/9/wAAHQAAAAEAAAACAAMAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAEAAcABQAGAAgAAQADAAIACgD9//3/AAA2ABAAAAABAAMAAgAFAAMAAgAEAAQABAAHAAAAAAAAAAAAAAABAAAAAgADAAQAEQAFABIAEwAhAGEABgBSAP3/MQBBAAcAFABRAP3/IgAjAHEA/f8VABYAMgD9/zQAQwBTAGIA/f/9//3//f/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A/f9+AP3/GgD9//3//f/9/3wAhloIAP3/LAD9/xgA/f/9//3/ewD9//3/DgBJAP3/BgD9//3//f/9/xEA/f/9//3/UwAXAGIAcwD9/20A/f9GAP3//f/9//3/bwD9//3/BQAFAFMA/f/9/xYAJwD9//3/egD9//3/9AT9/xoAJgD9/0YA/f8FAP3/bwBzAP3//f/9/0EA/f9AAEAAQQBjAGAAfwAQACoA/f/9//3/bABdAP3//f/9//3/MgD9//3/awAAAAEABwZYAD8AewBuAEgAPwD9/wsAHgD9//3//f8qAP3/WQAzADEAaABjAA8A/f8AAC4ASQAbABsA/f/9/xYA/f/9//3/MgBaBv3/HAD9//3/awD9//3//f9uAAgAKAA9AP3/HQD9/2jgOwD9//3/BAA8AP3/BgD9//3/HQBXAP3/IQD9//3//f8TAxEAfgD9/wIAMwAIAFgARgD9//3/PwARAAEG/f/9//3/XAApAP3//f/9//3//f9rSv3//f/9/ykA/f/9/3EA/f/9/wAA/f89AP3/QQAdAAEAAQABAAEAAQABAAQA/f87ABMA/f+qABsAUwBFADkA/f/9//3//f/9//3/PQD9/z0A/f8LAP3//f96AP3/LAByAP3//f/9/xUAdABfAP3/aQD9//3/AAD9/24AbwD9//3//f85ACEA/f9nACgAMQD9/xUAUQBTAEEANQBEAP3/5wRjAP3/JQD9//3/VgACAP3//f8FAAEAWQBXADUAdQBUAP3/dQAOAP3/NAD9/y4AeQD9//3//f8FAP3//f/9/yAA/f/9//3//f/9//3//f/9//3//f83APgE/f/9//3/WgD9/2AA/f8iAP3//f/9/28A/f/9/wEAPwD9//3//f/9/14AWQD9/ygAMAD9//3/fwD9/zgA/f/9/z4AXgBrAP3/fwD9//3/FABiAAIAAgACAAIAAgACAAIAAgACAAIADgD9//3//f/9/2QAHwD9//3/DQA=
But the image not renders on screen
What can I'm doing wrong?
Thanks

I'm not an image converting expert, but if it's a binary encoded image, try this :
let img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your binary data here');
// image now contains your picture
But I'm not sure this is correct data ... Anyways, try this, and let me know the result

For dealing with blobs coming from a server try the following
// Get the blob via an angular service - with response type "blob" as "json"
getBlob() {
return this.http_.get(`${this.url}/getBlob`, {responseType:"blob" as "json"});
}
//In your component
imageUrl: string;
getBlobUrl(){
this.blobService.getBlob().subscribe((data: Blob) => {
this.createImageFromBlob(data);
})
}
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageUrl= reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
<!--HTML-->
<div>
<img [src]="imageUrl">
</div>

If you have blob value, you can directly set the value in image tag in html..
Instead of this.imgStr = 'data:image/jpeg;base64,' + b64;
use this.imgStr = b64;
<img src="data:image/png;base64,{{imgStr}}" />

Related

How to convert type data buffer to image using typescript and react

I'm having problems showing an image brought from the database.
-> First I'll show you how this image is being stored:
Here I do the import and send it to the backend
import profile_default_image from "../../../other/imgs/profile_default_image.png";
resRegister = await register(user_name, user_email, user_password, profile_default_image);
profile_default_image generates a type string with value =/static/media/profile_default_image.a9136072d073801df253.png
This value is stored in the MYSQL database in a BLOB type field.
Below is the profileImage value of a row
-> Now I'll show you what's happening on the front
const [profileImage, setProfileImage] = useState("test");
useEffect(() => {
async function getUser() {
if (id) {
const res = await apiFindUserById(id);
const base64Flag = "data:image/jpeg;base64,";
const b64Image = await Buffer.from(res.data.profileImage.data).toString("base64");
setProfileImage(base64Flag + b64Image);
}
}
getUser();
}, []);
res.data returns the following:
Below I try to put the image on the screen
<div>
<img style={{ width: 200, height: 200, }}
src={profileImage}
alt="test"
/>
</div>
But the only result I have is this:
I gave a console.log in profileImage and it returned the value of: data:image/jpeg;base64,L3N0YXRpYy9tZWRpYS9wcm9maWxlX2RlZmF1bHRfaW1hZ2UuYTkxMzYwNzJkMDczODAxZGYyNTMucG5n, which basically a blank image.
I tried another way to do(found it here on stackoverflow)
const [profileImage, setProfileImage] = useState("test");
const arrayBufferToBase64 = (buffer: any) => {
let binary = "";
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
};
useEffect(() => {
async function getUser() {
if (id) {
const res = await apiFindUserById(id);
const imageStr = await arrayBufferToBase64(res.data.profileImage.data);
const base64Flag = "data:image/jpeg;base64,";
setProfileImage(base64Flag + imageStr);
console.log(profileImage);
}
}
getUser();
}, []);
I got the same result.
The original image is a default user avatar.
It could be that the problem is even when I'm storing this image in the database, can anyone help me? I'm very lost.
Thank you very much!!!

CSV File object to JSON in Angular

On the front end of my app I wanted to parse some data related to a CSV they upload. Through the file upload tool, I first get a FileList object and then pull the 1 file out of it.
I want to turn it into a json object which I could then iterate. I was thinking to user csv-parser from node, but I dont see a way to leverage a File object stored in memory.
How Can I accomplish this?
At first I was doing:
let f = fileList.item(0);
let decoder = new window.TextDecoder('utf-8');
f.arrayBuffer().then( data => {
let _data = decoder.decode(data)
console.log("Dataset", data, _data)
});
And that was passing the array buffer, and decoding the string. While I Could write a generic tool which process this string data based on \n and ',' I wanted this to be a bit more easier to read.
I wanted to do something like:
let json = csvParser(f)
is there a way to user csv-parser from node, (3.0.0) or is there another tool i should leverage? I was thinking that levering modules based on the browser ( new window.TextDecoder(...) ) is poor form since it has the opportunity to fail.
Is there a tool that does this? im trying to create some sample data and given a File picked from an input type="file" i would want to have this be simple and straight forward.
This example below works, but i feel the window dependancy and a gut feeling makes me think this is naive.
const f : File = fileList.item(0)
console.log("[FOO] File", f)
let decoder = new window.TextDecoder('utf-8');
f.arrayBuffer().then( data => {
let _data = decoder.decode(data)
console.log("Dataset", data, _data)
let lines = _data.split("\n")
let headers = lines[0].split(',')
let results = []
for ( let i = 1; i < lines.length; i++) {
let line = lines[i]
let row = {}
line.split(",").forEach( (item, idx) => {
row[headers[idx]] = item;
})
results.push(row)
}
console.log("JSON ARRAY", results)
})
The issue i run when i stop and do: ng serve is that it does not like using the arrayBuffer function and accessing TextDecoder from window, since that thost functions/classes are not a part of File and window respectively during build.
Any thoughts?
This is what I ended up doing, given the file input being passed into this function:
updateTranscoders(project: Project, fileList: FileList, choice: string = 'replace') {
const f: File = fileList.item(0)
//Reads a File into a string.
function readToString(file) : Promise<any> {
const reader = new FileReader();
const future = new Promise( (resolve,reject) => {
reader.addEventListener("load", () => {
resolve(reader.result);
}, false)
reader.addEventListener("error", (event) => {
console.error("ERROR", event)
reject(event)
}, false)
reader.readAsText(file)
});
return future;
}
readToString(f).then( data => {
let lines = data.split("\n")
let headers = lines[0].split(',')
let results = []
for (let i = 1; i < lines.length; i++) {
let line = lines[i]
let row = {}
line.split(",").forEach((item, idx) => {
row[headers[idx]] = item;
})
results.push(row)
}
if (choice.toLowerCase() === 'replace'){
let rows = project.csvListContents.toJson().rows.filter( row => row.isDeployed)
rows.push( ...results)
project.csvListContents = CsvDataset.fromJson({ rows: rows })
}else if (choice.toLowerCase() === 'append') {
let r = project.csvListContents.toJson();
r.rows.push(...results);
project.csvListContents = CsvDataset.fromJson(r);
}else {
alert("Invalid option for Choice.")
}
this.saveProject(project)
})
}
Now the CHOICE portion of the code is where I have a binary option to do a hard replace on CSV contents or just append to it. I would then save the project accordingly. This is also understanding that the first row contains column headers.

Angular 5 : How can i save a user with a BLOB avatar

I'm a newbie on Angular and i want to save a new user with an avatar, so how can i pass the Blob value of the avatar to my user Model so i can save it properly?
This is my code :
HTML
<input type="file" (change)="onSelectFile($event)" accept="image/x-png,image/gif,image/jpeg" value="{{image}}" id="avatar" ngModel name="avatar" #avatar="ngModel"/>
Typescript
image:any;
onSelectFile(event) {
var reader ;
reader = new FileReader;
reader.onload = (event) => {
console.log(reader.result);
this.image = reader.result;
console.log(this.image);
}
reader.readAsDataURL(event.target.files[0]);
}
The error i get when saving the user:
{"timestamp":"2018-11-24T13:29:13.222+0000","status":400,"error":"Bad Request","message":"JSON parse error: Cannot deserialize value of type `byte[]` from String \"\\fakepath\\IMG_20180808_023905.jpg\": Failed to decode VALUE_STRING as base64 (MIME-NO-LINEFEEDS): Illegal character ':' (code 0x3a) in base64 content; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `byte[]` from String \"\\fakepath\\IMG_20180808_023905.jpg\": Failed to decode VALUE_STRING as base64 (MIME-NO-LINEFEEDS): Illegal character ':' (code 0x3a) in base64 content\n at [Source: (PushbackInputStream); line: 1, column: 134] (through reference chain: org.vi.entities.User[\"avatar\"])","path":"/users"}
PS: the type of avatar field in user table is longblob
I don't encourage you to save images as blobs in the database, it's better to save just the name of the avatar and get the image to show after.
if you are interested in trying that I think this tutorial is good for that.
onSelectFile(event) {
let reader = new FileReader;
reader.onload = this.handle.bind(this);
reader.readAsArrayBuffer(this.file);
}
handle(readerEvt: any) {
let bytes = new Uint8Array(readerEvt.target.result);
for (let index = 0; index < bytes.byteLength; index++) {
this.image += String.fromCharCode(bytes[index]);
}
}
it is better idea to write images as text in database and send base64 string to server.
Then your function should look like this:
handle(readerEvt: any) {
let bytes = new Uint8Array(readerEvt.target.result);
let binaryText = '';
for (let index = 0; index < bytes.byteLength; index++) {
let binaryText += String.fromCharCode(bytes[index]);
}
this.image = btoa(binaryText);
}

How to read a text file and return it as a JSON object in Node JS?

I have a text file. I need to read the file inside a function and return it as a JSON object. The following is throwing an error "Unexpected token V in JSON at position 0" .
Server.js
fs.readfile('result.txt', 'utf8', function(err,data) {
if(err) throw err;
obj = JSON.parse(data);
console.log(obj);
});
result.txt looks like the following
VO1: 10 5 2
VO2: 5 3 2
I think I cannot use JSON.parse directly. How do I proceed?
Assuming the following:
Every line is separated by a newline character (\n)
Every line is separated by a : where the part in front of it is the key and the part behind it is a (space) separated string that should indicate the keys values as an array.
Below should work for your format:
fs.readfile('result.txt', 'utf8', function(err,data) {
if(err) throw err;
let obj = {};
let splitted = data.toString().split("\n");
for (let i = 0; i<splitted.length; i++) {
let splitLine = splitted[i].split(":");
obj[splitLine[0]] = splitLine[1].trim();
}
console.log(obj);
});
It could be issue with UTF-8 string format, Tried below code and it works
const resultBuffer = fs.readFileSync('result.txt');
const resultData = JSON.parse(resultBuffer.toString().trim());
Thanks to Baao for providing that answer.
As another flavor of solution, if you don't have any ":" for perhaps a list of files you could always code in a key like so:
var data = fs.readFileSync(pathAndFilename);
var testData = {};
var splitList = data.toString().split('\r\n');
for (var i = 0; i < splitList.length; i++) {
testData['fileNumber' + i.toString()] = splitList[i];
}
You need to parse the text file by yourself. You can use RegExp or some other means to extract the values, create an object out of that and then JSON.stringify it.
improving upon #baao answer:
const fs = require("fs")
fs.readFile('.czrc', 'utf8', function (err, data) {
if (err) {
console.error(err)
throw "unable to read .czrc file.";
}
const obj = JSON.parse(data)
});
Your result.txt is not valid json.
Valid json would look like this.
{
"VO1": [10, 5, 2],
"VO2": [5, 3, 2]
}

Windows Phone send Bitmap using multipart/form-data

My request need to look like this:
Content-Type: multipart/form-data; boundary=---BOUNDARY
-----BOUNDARY
name="receipt_photo"; filename="image_filename.jpg"
Content-Type: image/jpeg
-----BOUNDARY
I am trying to send it using following code
public async static Task addPhotosToReceipt(BitmapImage image, int idReceipt)
{
User user = PhoneApplicationService.Current.State["user"] as User;
if (user.customer.token != null)
{
RestConnector rc = new RestConnector();
byte[] data;
try
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(image);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, image.PixelWidth, image.PixelHeight, 0, 100);
data = ms.ToArray();
}
string response = await rc.postAsyncData("/api/v1/receipts/" + idReceipt + "/receipt_photos/?token=" + user.customer.token, data);
if (response.Contains("error"))
{
MessageBox.Show(response);
}
}
catch (Exception ex)
{
}
}
}
//in RestConnector class
public async Task<string> postAsyncData(string adress, byte[] file)
{
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent("---BOUNDARY"))
{
content.Add(new StringContent("-----BOUNDARY\nname=\"receipt_photo\"; filename=\"image_filename.jpg\"\nContent-Type: image/jpeg\n-----BOUNDARY"));
content.Add(new StreamContent(new MemoryStream(file)));
using (var message = await client.PostAsync(basicUrl + adress, content))
{
var input = await message.Content.ReadAsStringAsync();
return input;
}
}
}
}
In response I should get URL's to uploaded photos, but instead I got URL's to default photos. I think there is something with my request because on android it works fine.
Maybe I choosed wrong way to create byte from my bitmap?