How to process raw jpeg data into a file in javascript - javascript

I'm trying to create a jpeg file from raw data in javascript
I've been using the google file picker api to allow users to select their images from drive and import into my application, but when I make the request to download the image google responds with raw data that looks like this:
Google's response
I have tried placing that data into a blob with:
var blob = new Blob([res.text], {type: 'image/jpeg'})
I have also tried placing the data into a file.
var file = new File([res.text], 'image.jpeg', {type:"image/jpeg"})
However the file only renders black pixels. How can I go about generating a jpeg file from that data so I can upload to my server?
Update(Solution):
I switched my request api to fetch and used .blob() on the response

For superagent see http://visionmedia.github.io/superagent/#parsing-response-bodies -> Binary and http://visionmedia.github.io/superagent/#response-properties -> Response body.
You need to use .responseType('blob') and res.body.
https://stackblitz.com/edit/js-so-how-to-process-raw-jpeg-data-into-a-file-in-javascript

Related

Generate HTTP response from raw file data in JavaScript

I need to be able to take the raw data from any file and generate a response object within a service worker.
Short explanation:
I have a website that takes file names, paths, mime types and raw text and stores it in cache. If I make a request to a file with that path and name, a service worker responds with that raw data.
Here is the very basic service worker response code:
self.addEventListener("fetch", async event =>
event.respondWith(caches.match(event.request))
);
This system works fine for HTML, CSS, JS and probably other files, but not for PNGs. I keep getting the image not found image:
I have checked that the correct mime type is being sent and the correct data is stored in cache. I have tried putting the data in cache with the text I find in notepad after opening the PNG, and the text result of a fetch request to an actual PNG file, using the .text() method.
Here are partial images of both:
Notepad++:
Fetch:
This data in the images is put into cache with this code:
cache.put(
rawFileText,
new Response(
"filePath/example.html",
{
status: 200,
headers: new Headers({
"content-type": "image/png" + "; charset=utf-8",
}),
},
),
);
More background info:
This is for a web code editor I am working on. When I want to run code in the editor:
website1 will create an iframe with website2 as source
website1 post messages all the file names, paths, mime types and raw text containing code, images, etc. (by raw data I mean whatever you would see if you opened the file with notepad)
then the iframe (website2) stores the file names and data as cache
when a request is made to any file stored in website2's cache, the service worker responds with whatever data is under the file name
The reason I use 2 different websites is to avoid conflicts with the editor website's files, local storage, and everything else. There could still be conflict with the second website's cache and service worker but that isn't a problem in my case.

Is file_get_contents in PHP the same as toDataUrl in Javascript?

I want to use an API to compress images. It says the input can as well be a buffer (string with binary), for example:
$sourceData = file_get_contents("unoptimized.jpg");
$resultData = \Tinify\fromBuffer($sourceData)->toBuffer();
In my understanding, they use file_get_contents to create that buffer from a file.
In my case, I already got an canvas image using a React application. To make the API call, I create a data URI, using .toDataURL() looking something like this:
data:image/png;base64,iVBORw0KGgoAAAANSUh... // lots of letters
So can I just use this data URI instead of file_get_contents, because both commands actually do the same in different languages, or is there a difference? Like:
$sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUh...'
\Tinify\fromBuffer($sourceData)->toBuffer();
API Reference: https://tinypng.com/developers/reference/php
file_get_contents returns the content of a file as string, and that string exactly represents the content of the file.
.toDataURL() gives you a data url. The data:image/png;base64, part tells that the following data represents a png and that the data is base64 encoded.
To get the same data representation as you get with file_get_content you would need to decode the iVBORw0KGgoAAAANSUh...
So yes, both give you the content of a file, but they don't do that in the same way.
To toBlob on the other hand will return a Buffer containing the data in the same representation as file_get_contents would do.
Assuming you have a PNG file named input.png, the following two pieces of code produce the same result:
Read the image data from the PNG file:
$sourceData = file_get_contents('input.png');
Read the image data from a data: URL generated from the PNG file:
// Generate the 'data:' URL
$url = 'data:image/png;base64,'.base64_encode(file_get_contents('input.png'));
// Read the image data from the 'data:' URL
$sourceData = file_get_contents($url);
The second piece of code works only if fopen wrappers are enabled on the server where the file_get_contents() is executed.
It doesn't make much sense to use the second fragment of code in a single script (because it does a redundant encoding and decoding) but it makes a lot of sense if the encoding and restoring (decoding) happen in different scripts.
They can be part of the same application (the script that encodes the data stores it in the database, the other script loads from the database, restores the image data and uses it) or the decoding could happen in a remote application that sends the data URL over the Internet to be decoded and used by a different application.

how to input a binary image file while uploading profile image file to IBM Connections using REST API

I am using REST client to upload a profile photo to IBM connections but i am struck at the part where you have to send binary image file along with the PUT request. So far I've done this:-
request.put("https://servername.com"/profiles/photo.do?
key="profileuserID"),
ContentType:image/jpeg
i have tried to put insert image by encoding it into base64 format or adding into file field in REST client. But it always returns nothing. It does remove the previous profile picture but it doesnt upload the new one.
Now i want to ask how to include binary image file in the request payload?

Saving AJAX stream to a PDF file

I'm trying to save the result of a XMLHTTPRequest to a PDF file.
I am communicating with a server I am calling to get a chunk of data formatted as PDF data.
I'm using XMLHTTPRequets to log into the server, then make a search request which in return creates a PDF which is streamed back to me though the XMLHTTPRequest.
I need to save that result as a PDF so I can later open it in Acrobat.
When I save the response text to a file the result is not a valid PDF. The request is doing something to the stream which makes it invalid as a PDF.
I have no control over that server so I cant make it send back a link to a temporary valid PDF file.
Is there a way around that ?
Is there a way to encode that stream into a valid PDF file ?
I am using Javascript for that application.
Thanks
Erez
what you could do is return from your http server an xml file like the following:
<resp><![CDATA[YOURPDFSTREAM]]></resp>
and them retrieve the RESP node to build your pdf file.
Don't forget to encode your stream in the desired encoding format as well.

Display Blob data retrieved from MySQL Database using JavaScript

Using a web service, I was able to retrieve some data from a MySQL Database. The database has an image saved in it, which had the file type of BLOB. This is what my web service returns when it comes to the image:
<image>
/9j/4AAQSkZJRgABAQEAYABgAAD/7TaeUGhvd.....RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQB//Z
</image>
Now I am having trouble making my JavaScript application convert this data and then display it as an image. I researched on it a bit and found a couple of tutorials online but somehow they did not work for me....can anyone please help me with this issue? What is the simplest way I can convert BLOB data to an image? Thanks in advance!
Assuming the blob has base64 encoded PNG data, you can use data-uri to set data directly to image e.g.
var imgdata = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
$('#myimg').attr('src', "data:image/png;base64,"+imgdata)
Assumption here is that data returned from server is base64 encoded, but if that is not the case you can see various options but ultimately you may have to do proper conversion in server side, in that case why not just return the url to image and create a API on server side to return images from blob
Here is a jsfiddle in action http://jsfiddle.net/anuraguniyal/4DEtH/5/
Edit:
I am not sure what language you use server side but process will be same for each language e.g.
>>> s='\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x05\x00\x00\x00\x05\x08\x06\x00\x00\x00\x8do&\xe5\x00\x00\x00\x1cIDAT\x08\xd7c\xf8\xff\xff?\xc3\x7f\x06 \x05\xc3 \x12\x84\xd01\xf1\x82X\xcd\x04\x00\x0e\xf55\xcb\xd1\x8e\x0e\x1f\x00\x00\x00\x00IEND\xaeB`\x82'
>>> import base64
>>> base64.b64encode(s)
'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
i.e. take all data, as will be stored in file (not the png marker too), not just raw image data and encode it

Categories

Resources