Set Image src from image blob - javascript

I have trying to request an image from an API and set the src of an img in my web page. The API returns a blob that represents a .png file. At this time, I'm requesting the image using the following:
const fetchResult = await fetch(imageApiUrl);
const resultBlob = await fetchResult.blob();
console.log(resultBlob);
In the console, I can see:
Blob {size: [some number], type: "image/png" }
So, I know that I have a result. I assume a blob. I now need to set this blob as the source of an img in my HTML, which looks like this:
<img id="profilePicture" alt="Profile Picture" height="250" width="250" />
I have this:
var profilePicture = document.getElementById('profilePicture');
How do I set the src of the profilePicture element to the blob?

You could use URL.createObjectURL in order to create a temporary URL that points to the in-memory image:
let url = URL.createObjectURL(resultBlob);
const img = document.getElementById('profilePicture');
img.src = url;

Related

Display img receive from API as Stream

How can I read a stream from the api to display it in the src of an img tag ?
With this response I just want to display it in a <img src="myStream" />
My first error was to try to display a pdf file in an <img/> tag. I used an <iframe /> instead.
Also I had to use fetch to make the request and after use response.blob() :
const myFunctionToConvertHttpResponseToFileUrl = () => async {
const response = await fetch('myurl.com')
const myBlob = response.blob()
this.fileURL = URL.createObjectURL(myBlob);
}
And After in the html
<iframe :src="fileUrl" type="application/pdf" />

Is it possible to display an image that has been selected by an input element?

I wish to display an input element's selected image. Can this be performed on a local file, accessing the image client side, or would I need to upload the image to a server?
Here's my attempt in React. I can access the correct file name from the input element using inputElem.files[0].name. As soon as I am trying to set an image element to it, the broken image icon is displayed, and no error is surfaced.
const App = () => {
// state to keep track of img elements src. The default works fine.
const [imgSrc, setImgSrc] = useState('/images/test.jpg')
function handleImgUpload() {
const url = '/images/' + e.target.files[0].name
setImgSrc(url)
console.log(url) // /images/26e3e793-98f5-4720-9f82-8963276d5e27.JPG
}
function handleImgLoadSuccess() {
console.log('image loaded!')
}
function handleImgLoadError() {
console.log('image not loaded')
}
return (
<div>
<div>
<label htmlFor="img">Select an image:</label>
<input
type="file"
id="img"
name="img"
accept="image/png, image/jpeg"
onChange={(e) => handleImgUpload(e)}
/>
</div>
<img
src={imgSrc}
alt="Your upload"
onLoad={handleImgLoadSuccess}
onError={handleImgLoadError}
/>
</div>
)
}
In the console, however, the url seems to be correct.
<img src="/images/26e3e793-98f5-4720-9f82-8963276d5e27.JPG" height="100" width="200" alt="Input" class="jsx-855240488">
Hey – I see what you're trying to do, but it doesn't look like this will work. You need to create a new file reader.
const showTempImage = (e) => {
const file = e.target.files[0];
const img = document.createElement("img");
const reader = new FileReader();
reader.addEventListener('load', (e) => {
img.src = e.target.result;
});
reader.readAsDataURL(file);
// Append the img tag to the dom somewhere
}
This did the trick by creating a correct blob url.
const inputImg = e.target.files[0]
const url = URL.createObjectURL(inputImg)
// blob:http://localhost:3000/test-img.jpg
The resulting file stays in memory and needs to be removed in order to create memory leaks.
URL.revokeObjectURL(url)
This also seems to be accomplishable with FileReader, though there are differences.

Get src type of img or video tag (not extension)?

Say I have an image tag such as this:
<img src="smiley.gif" alt="Smiley face" height="42" width="42">
I know I can get the src by using myImageEl.src.
However, how do I get the type of the src (.gif in this case)?
Basically, my end goal is to pass the file type to window.URL.createObjectUrl()
let src = imageEl.src;
let srcType = src.type; // Here I need to get the type
let videoFile = new Blob([src], {type: srcType});
let videoSrc = window.URL.createObjectURL(videoFile);
var imgSrc = 'image.jpeg';
var ext = imgSrc.replace(/^.*\./, '')
I am not very good with regex, but using regex to fetch the extension of the image or video is the a good way of accomplishing this task.
For precision sake you could compare ext with a predeifined set of array
imgTag = ['jpg', 'jpeg', 'gif', 'png'];
vidTag = ['mp4', '3gp']
then you can compare using a forEach loop
From your tags I noticed you want to access image source type from javascript, if so you can use following codes base on what attributes we have for that image element:
for example if image element has id :
var imageElement = document.getElementById(id);
var imgsrc = imageElement.src;
var imgType = imgsrc.split('.').pop();
imgType will be the type of your image.
And if your image element doesn't have id, you can use document.getElementsByTagName("img") instead of document.getElementById(id) and code will look like this
var imageElement = document.getElementsByTagName("img");
var imgsrc = imageElement.src;
var imgType = imgsrc.split('.').pop();

Blob as source docx/pptx/xlsm/etc as iframe

I am having a problem identical to this enter link description here (unanswered) question. Is it possible to create an iframe of docx/pptx/xlsm/etc with a blob? For reference, here's some code
AngularJS snippet to have docx iframes
get_file_data().then(function(response){ //assume get_file_data works
memtype = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
var blob = new Blob([response.data], {type: memtype});
var blob_url = $window.URL.createObjectUrl(blob);
var office_url = "http://view.officeapps.live.com/op/embed.aspx?src=";
var url = office_url + blob_url;
$scope.content = $sce.trustAsResourceUrl(url);
And then in my html file:
<iframe ng-src = "{{content}}"> </frame>
It doesn't work likely because blob_url has blob:// as a prefix, how can I fix this to make it work? Or is this something that can't be done? For some reason, this approach works for pdf files

How to get base64 encoded data from html image

I have a registration form where users can choose an avatar. They have 2 possibilities:
Choose a default avatar
Upload their own avatar
In my HTML page I have this.
<img id="preview" src="img/default_1.png">
It displays the chosen avatar.
I use the File Api to let users upload their own image.
That makes the src of the HTML image to something like this.
<img id="preview" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA... />
When they post the registration form. The data will be sent to a REST service.
I can send the base64 encoded data when a user uploaded an avatar himself. But how do I handle the default avatar? It is an url instead of base64 encoded data.
You can try following sample
http://jsfiddle.net/xKJB8/3/
<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );

Categories